Bug: Stale 闭包 — 事件处理函数 uses 旧状态值
错误信息
事件处理函数 captures stale 状态值
快速摘要
事件处理函数创建 in 上一个渲染 captures 状态值 从那个渲染, 不 current one.
为什么发生
事件处理函数 captures 状态从 渲染它 是创建 in
useEffect 使用空 deps captures 初始状态
setTimeout/setInterval 回调 captures 旧状态
最小示例
✗ 错误代码
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1); // count is always 0!
}, 1000);
return () => clearInterval(id);
}, []); // count not in deps✓ 修复代码
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(prev => prev + 1); // Uses latest value
}, 1000);
return () => clearInterval(id);
}, []); updater 函数 prev => prev + 1 总是接收 latest 状态, avoiding stale 闭包 problem.
如何诊断
Log 状态值 内部处理函数到 see 如果它's stale
检查如果处理函数是 memoized 使用 stale dependencies
Look for 闭包创建 in 副作用使用不完整 deps
如何修复
Use updater 函数表单:
setCount(prev => prev + 1)添加状态到 dependency 数组的 useEffect/useCallback
Use ref 到持有 latest 值如果你 能't 添加它 到 deps
如何预防
Use updater 函数 for 状态那个 depends on 上一个值
总是包含所有 used 值 in dependency 数组
Use useRef for 值那个需要到 是读取 in stale 闭包
相关资源
相关术语
相关课程
- useEffect
学习到 avoid stale 闭包.