求助:Mobx的computedFn未实现记忆化功能?
问题:computedFn记忆化失效,每次调用都执行内部逻辑
在React项目中使用computedFn时,发现它未实现记忆化——即使传入相同参数,每次调用都会执行内部逻辑。示例代码如下:
const getComp = computedFn((num: number) => { console.log('**** get computed num'); return num * num; }); function testComputedFn() { for (let i = 0; i < 10; i++) { getComp(8); } }
调用testComputedFn后,控制台打印了10次**** get computed num,记忆化完全失效。
解决方案
你使用的computedFn(通常来自@vue/reactivity)的记忆化逻辑不是基于调用参数做缓存,而是依赖内部的响应式依赖追踪:只有当函数内部访问了响应式变量,且这些变量未发生变化时,才会返回缓存值;如果函数没有任何响应式依赖,哪怕参数完全相同,每次调用都会重新执行。
针对你的需求,有两种可行方案:
方案1:改用基于参数的记忆化工具
如果需要根据传入参数做记忆化,推荐使用通用记忆化工具(比如lodash.memoize),或者在React组件内使用useMemo(需配合依赖数组):
示例:使用lodash.memoize
import memoize from 'lodash.memoize'; const getComp = memoize((num: number) => { console.log('**** get computed num'); return num * num; }); function testComputedFn() { for (let i = 0; i < 10; i++) { getComp(8); // 仅打印一次 } }
方案2:结合响应式变量使用computedFn
如果一定要使用computedFn,需要将参数包装为响应式变量,让函数内部依赖该变量:
import { computedFn, ref } from '@vue/reactivity'; // 将参数转为响应式ref const numRef = ref(8); // 函数内部访问响应式变量 const getComp = computedFn(() => { console.log('**** get computed num'); return numRef.value * numRef.value; }); function testComputedFn() { for (let i = 0; i < 10; i++) { getComp(); // 仅打印一次 } // 当响应式变量更新时,才会重新执行函数 numRef.value = 9; getComp(); // 再次打印 }
内容的提问来源于stack exchange,提问作者flyingbee
相关产品推荐
相关产品推荐

