# 类型错误：无法读取 null 的属性（读取 'Provider'）

- **ID:** `react/usecontext-outside-provider-null`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

尝试从 null 的 context 对象中解构或访问 Provider 属性，通常是因为 context 未使用 createContext() 创建或导入不正确。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| React 16.8+ | active | — | — |
| React 17.0.2 | active | — | — |
| React 18.2.0 | active | — | — |

## 解决方案

1. ```
   Ensure createContext is called and exported correctly. Example: export const MyContext = createContext(); then import { MyContext } from './context'; not import MyContext from './context'; if it's a named export.
   ```
2. ```
   If using default export, change to: import MyContext from './context'; then use MyContext.Provider. Check that the export statement in the context file matches the import.
   ```

## 无效尝试

- **Adding a null check before accessing Provider** — This masks the error but the context is still null, so the Provider component will be undefined and React will throw another error. (50% 失败率)
- **Using a default value for the context** — Default value only applies when consuming context with useContext, not when accessing Provider or Consumer from the context object itself. (60% 失败率)
- **Wrapping everything in a try-catch** — The error occurs at render time; try-catch won't catch it unless you use an error boundary, and it doesn't solve the root cause. (70% 失败率)
