https://mobx.js.org/refguide/computed-decorator.htmlthat if you create a computed property but don't use it anywhere in a reaction, it will not cache its value and recompute more often than seems necessary
when / autorun / reaction 会假设你的依赖是除了包含 reactive 值的其他部分是不包含任何副作用的,所以会缓存,而在这些之外手动访问,可能不能保证不产生副作用。类似如果写出像这样的 getter:
get d() { return [Date.now()] }
是否每次时间变化都会触发 autorun ?结果显然是不会,因为 Date.now()并不是 reactive 的。而 get d() 却并不是一个纯函数。
如果希望函数执行的结果每次都能缓存下来,需要自己封装一层,通过 reaction 将结果缓存下来,类似下面这样
const useMobxMemo = (computedFunction) => {
const value = computed(computedFunction);
const state = {
value,
};
reaction(() => value.value, () => {
state.value = value.value;
});
return state.value;
};