react
runtime_error
ai_generated
true
警告:检测到过时的闭包。传递给 useEffect 的回调引用了一个可能已过时的变量。
Warning: A stale closure was detected. The callback passed to useEffect references a variable that may be outdated.
ID: react/stale-closure-useeffect
90%修复率
85%置信度
1证据数
2023-05-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.8.0 | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 18.2.0 | active | — | — | — |
根因分析
useEffect 回调捕获了来自之前渲染的变量,当该变量发生变化时,由于依赖数组缺失或不完整,effect 仍然使用旧值。
English
A useEffect callback captures a variable from an earlier render, and when that variable changes, the effect still uses the old value because the dependency array is missing or incomplete.
官方文档
https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies解决方案
-
Add all variables referenced inside the effect to the dependency array: `useEffect(() => { console.log(count); }, [count]);` -
Use the functional update form of setState or useReducer if the stale variable is a state value: `setCount(prev => prev + 1)`
-
Use `useRef` to hold the latest value and update it via an effect: `const countRef = useRef(count); countRef.current = count;` then access `countRef.current` inside the effect.
无效尝试
常见但无效的做法:
-
80% 失败
The effect never re-runs when the captured variable changes, so the closure remains stale indefinitely.
-
75% 失败
The variable is still captured at the time of effect creation; if it changes, the effect still uses the old value.
-
60% 失败
If the ref is not manually updated when the variable changes, it still holds the old value.