react runtime_error ai_generated true

TypeError:无法读取 null 的属性(读取 'focus')

TypeError: Cannot read properties of null (reading 'focus')

ID: react/ref-object-null-on-mount

其他格式: JSON · Markdown 中文 · English
90%修复率
85%置信度
1证据数
2023-05-18首次发现

版本兼容性

版本状态引入弃用备注
React 18.2.0 active
React 19.0.0-rc.2 active

根因分析

访问 ref 对象时其为 null,因为组件尚未挂载或 ref 错误地附加到了无状态组件。

English

A ref object is null when accessed because the component has not mounted yet or the ref is incorrectly attached to a stateless component.

generic

官方文档

https://react.dev/reference/react/useRef

解决方案

  1. Access the ref inside a useEffect hook with an empty dependency array to ensure the component is mounted: useEffect(() => { if (ref.current) { ref.current.focus(); } }, []);
  2. Use a callback ref to handle the ref assignment: const inputRef = useCallback(node => { if (node) { node.focus(); } }, []); <input ref={inputRef} />
  3. If using a function component, wrap it with React.forwardRef and pass the ref to a DOM element inside: const MyComponent = React.forwardRef((props, ref) => <input ref={ref} />);

无效尝试

常见但无效的做法:

  1. 90% 失败

    The ref is not attached until after the component mounts, so it is null initially.

  2. 70% 失败

    This creates a dummy element that is not connected to the DOM, so methods like focus() may not work as expected.

  3. 80% 失败

    Function components cannot receive refs directly; they must be wrapped in forwardRef.