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

- **ID:** `react/typeerror-cannot-read-properties-of-null-reading-usestate`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

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

## 版本兼容性

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

## 解决方案

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.
   ```

## 无效尝试

- **Wrap the entire component in a React.StrictMode component** — StrictMode only highlights potential issues; it doesn't fix the root cause of hooks being called outside a component. (95% 失败率)
- **Add a constructor in a function component to initialize state** — Function components do not support constructors; this will cause a syntax error or undefined behavior. (100% 失败率)
- **Use class component syntax without converting fully** — Mixing class and function component patterns leads to hooks being called in invalid contexts, exacerbating the error. (90% 失败率)
