react runtime_error ai_generated true

TypeError: 无法读取 null 的属性 'useState'

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

ID: react/typeerror-cannot-read-properties-of-null-reading-usestate

其他格式: JSON · Markdown 中文 · English
88%修复率
85%置信度
1证据数
2024-03-15首次发现

版本兼容性

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

根因分析

React 的 useState 钩子是在 null 上下文中被调用的,通常是因为使用钩子的组件不是有效的 React 函数组件,或者钩子在组件的渲染周期之外被调用。

English

React's useState hook is being called from a null context, typically because the component using hooks is not a valid React function component or the hooks are being called outside of a component's render cycle.

generic

官方文档

https://react.dev/reference/react/useState

解决方案

  1. Ensure the component is a valid React function component that returns JSX and does not call hooks conditionally or inside loops. Example: function MyComponent() { const [state, setState] = useState(initialValue); return <div>{state}</div>; }
  2. Move all hook calls to the top level of the component body, never inside callbacks or after early returns. Use a linter like eslint-plugin-react-hooks to catch violations: npx eslint --fix src/
  3. If using custom hooks, verify they are invoked inside a function component and not in a utility function or event handler. Wrap the call in a component if needed.

无效尝试

常见但无效的做法:

  1. Wrap the entire component in a React.StrictMode component 95% 失败

    StrictMode only highlights potential issues; it doesn't fix the root cause of hooks being called outside a component.

  2. Add a constructor in a function component to initialize state 100% 失败

    Function components do not support constructors; this will cause a syntax error or undefined behavior.

  3. Use class component syntax without converting fully 90% 失败

    Mixing class and function component patterns leads to hooks being called in invalid contexts, exacerbating the error.