react
runtime_error
ai_generated
true
类型错误:无法读取 null 的属性(读取 'current')
TypeError: Cannot read properties of null (reading 'current')
ID: react/ref-object-not-initialized
87%修复率
83%置信度
1证据数
2023-05-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.8+ | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 18.2.0 | active | — | — | — |
根因分析
尝试访问 null 的 ref 上的 .current 属性,通常是因为 useRef() 调用时没有初始值,或者 ref 未正确附加到 DOM 元素。
English
Attempting to access .current on a ref that is null, often because useRef() was called with no initial value or the ref was not properly attached to a DOM element.
官方文档
https://reactjs.org/docs/hooks-reference.html#useref解决方案
-
Ensure the ref is attached to a DOM element: const myRef = useRef(null); return <div ref={myRef}>...</div>. Then access myRef.current only after the component mounts, e.g., inside useEffect or an event handler. -
If using forwardRef, make sure the child component forwards the ref to a DOM element: const Child = forwardRef((props, ref) => <input ref={ref} />);
无效尝试
常见但无效的做法:
-
Setting useRef(null) explicitly
40% 失败
If the ref is not attached to a DOM element, it remains null. The fix is to attach it, not to change the initial value.
-
Using useEffect to check if ref.current exists
50% 失败
A null check only masks the error; the underlying issue (ref not attached) persists.
-
Using createRef() instead of useRef()
60% 失败
createRef() returns { current: null } in function components and will not persist across renders; it's for class components.