react
runtime_error
ai_generated
true
警告:检测到过时闭包。传递给 useCallback 的回调引用了一个可能已过时的变量。
Warning: A stale closure was detected. The callback passed to useCallback references a variable that may be outdated.
ID: react/use-callback-stale-closure
90%修复率
85%置信度
1证据数
2023-11-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 18.2.0 | active | — | — | — |
| React 19.0.0-rc.1 | active | — | — | — |
根因分析
useCallback 钩子在其闭包中捕获了一个未在依赖数组中列出的变量,导致回调引用了过时的值。
English
The useCallback hook captures a variable in its closure that is not listed in its dependency array, causing the callback to reference a stale value.
官方文档
https://react.dev/reference/react/useCallback解决方案
-
Add the missing variable to the dependency array of useCallback. For example: const handleClick = useCallback(() => { console.log(count); }, [count]); -
Use a ref to store the variable and access it inside the callback without adding it to dependencies. Example: const countRef = useRef(count); countRef.current = count; const handleClick = useCallback(() => { console.log(countRef.current); }, []); -
Upgrade to React 19 and use the new use hook which automatically tracks dependencies.
无效尝试
常见但无效的做法:
-
70% 失败
This ignores the stale closure issue and may still reference outdated values, leading to bugs.
-
80% 失败
useMemo is for values, not callbacks, and does not solve the dependency tracking issue.
-
90% 失败
This forces the callback to always be stale, breaking any logic that relies on current state.