react
runtime_error
ai_generated
true
类型错误:无法读取未定义的属性(读取 'dispatch')
TypeError: Cannot read properties of undefined (reading 'dispatch')
ID: react/usecontext-must-be-within-provider
92%修复率
88%置信度
1证据数
2023-03-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.8+ | active | — | — | — |
| React 17 | active | — | — | — |
| React 18 | active | — | — | — |
| React 19 | active | — | — | — |
根因分析
useContext 在对应的 Context Provider 外部调用,导致上下文值为 undefined。
English
useContext is called outside the corresponding Context Provider, so the context value is undefined.
官方文档
https://react.dev/reference/react/useContext解决方案
-
Ensure the component is rendered inside the corresponding Context Provider. For example, move the component inside the Provider tree: // App.jsx import { MyProvider } from './MyContext'; import ChildComponent from './ChildComponent'; function App() { return ( <MyProvider> <ChildComponent /> </MyProvider> ); } export default App; -
If the component must sometimes exist outside the Provider, provide a fallback default value in createContext: const MyContext = createContext({ dispatch: () => console.warn('dispatch called outside Provider') }); -
Add a guard clause in the component to render nothing or a fallback UI when context is missing: function ChildComponent() { const context = useContext(MyContext); if (!context) return null; // or <FallbackUI /> const { dispatch } = context; // ... }
无效尝试
常见但无效的做法:
-
60% 失败
Maskes the error but does not solve the structural issue; dispatch will be a no-op if no Provider is present, leading to silent failures.
-
70% 失败
Only works in tests or specific scenarios; in production, the real Provider is missing, so the mock may not provide the correct dispatch function.
-
50% 失败
Prevents the error but dispatch becomes undefined, causing subsequent calls to fail with 'dispatch is not a function'.