react
runtime_error
ai_generated
true
TypeError: Cannot read properties of null (reading 'focus') when using ref callback
ID: react/ref-callback-null-on-unmount
90%Fix Rate
85%Confidence
1Evidence
2023-09-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| React 18.2.0 | active | — | — | — |
| React 17.0.2 | active | — | — | — |
Root Cause
A ref callback receives null when the component unmounts, and code attempts to access properties or methods on the ref without checking for null.
generic中文
当组件卸载时,ref 回调接收 null,而代码在未检查 null 的情况下尝试访问 ref 的属性或方法。
Official Documentation
https://react.dev/reference/react/useRef#ref-callbackWorkarounds
-
95% success Add a null check before accessing properties on the ref. Use optional chaining or a guard clause.
Add a null check before accessing properties on the ref. Use optional chaining or a guard clause.
-
90% success Use a ref callback with cleanup to handle the null case gracefully, especially when using third-party libraries.
Use a ref callback with cleanup to handle the null case gracefully, especially when using third-party libraries.
中文步骤
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.
Dead Ends
Common approaches that don't work:
-
50% fail
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% fail
setTimeout doesn't guarantee the component is still mounted; if unmount occurs during the delay, ref.current is null.