类型错误:无法读取 null 的属性(读取 'Provider')
TypeError: Cannot read properties of null (reading 'Provider')
ID: react/usecontext-outside-provider-null
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.8+ | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 18.2.0 | active | — | — | — |
根因分析
尝试从 null 的 context 对象中解构或访问 Provider 属性,通常是因为 context 未使用 createContext() 创建或导入不正确。
English
Attempting to destructure or access a property like Provider from a context object that is null, typically because the context was not created with createContext() or was imported incorrectly.
官方文档
https://reactjs.org/docs/context.html解决方案
-
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. -
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
50% 失败
This masks the error but the context is still null, so the Provider component will be undefined and React will throw another error.
-
Using a default value for the context
60% 失败
Default value only applies when consuming context with useContext, not when accessing Provider or Consumer from the context object itself.
-
Wrapping everything in a try-catch
70% 失败
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.