react
runtime_error
ai_generated
true
类型错误:无法读取 null 的属性(读取 'focus')当使用 ref 回调时
TypeError: Cannot read properties of null (reading 'focus') when using ref callback
ID: react/ref-callback-null-on-unmount
90%修复率
85%置信度
1证据数
2023-09-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 18.2.0 | active | — | — | — |
| React 17.0.2 | active | — | — | — |
根因分析
当组件卸载时,ref 回调接收 null,而代码在未检查 null 的情况下尝试访问 ref 的属性或方法。
English
A ref callback receives null when the component unmounts, and code attempts to access properties or methods on the ref without checking for null.
官方文档
https://react.dev/reference/react/useRef#ref-callback解决方案
-
Add a null check before accessing properties on the ref. Use optional chaining or a guard clause.
-
Use a ref callback with cleanup to handle the null case gracefully, especially when using third-party libraries.
无效尝试
常见但无效的做法:
-
50% 失败
useRef still holds a reference to the DOM node but can become stale; accessing .current after unmount may still be null or cause memory leaks.
-
80% 失败
setTimeout doesn't guarantee the component is still mounted; if unmount occurs during the delay, ref.current is null.