You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

首次使用React.useContext遇undefined错误,求排查解决

解决React useContext报错:Uncaught TypeError: React.useContext(...) is undefined

核心问题分析

报错本质是调用useContext(UserContext)返回了undefined,主要由两个原因导致:组件不在Context Provider的覆盖范围内,或者Provider本身存在代码错误导致无法正常提供上下文。

问题1:UserStorage组件存在未定义状态

你的UserStorage代码中,getUser函数调用了setLogin(true),但并未声明login状态和setLogin方法,这会先触发报错,间接导致Context无法正常工作。

问题2:使用Context的组件未被Provider包裹

Header和LoginForm调用了useContext(UserContext),但如果它们没有被<UserStorage>(即UserContext.Provider的载体组件)包裹,useContext会返回Context的默认值——你创建Context时未传默认值,所以返回undefined,解构{ data }或{ userLogin }自然报错。


分步修复方案

1. 修复UserStorage中的未定义状态

在UserStorage组件里添加login状态声明:

import React from 'react';
import { TOKEN_POST, USER_GET } from 'Api';

export const UserContext = React.createContext();

export const UserStorage = ({ children }) => {
  const [data, setData] = React.useState(null);
  // 添加login状态声明
  const [login, setLogin] = React.useState(false);

  async function getUser(token) {
    const { url, options } = USER_GET(token);
    const response = await fetch(url, options);
    const json = await response.json();
    setData(json);
    setLogin(true); // 现在setLogin已定义
    console.log(json);
  }

  // 其余代码保持不变
};

2. 确保所有使用Context的组件被Provider包裹

在根组件(如App.js)中,用<UserStorage>包裹所有需要访问UserContext的组件:

import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import Header from './Header';
import LoginForm from './LoginForm';
import { UserStorage } from './UserContext';

function App() {
  return (
    <UserStorage>
      <BrowserRouter>
        <Header />
        {/* 所有需要访问UserContext的组件都要放在这里面 */}
        <LoginForm />
      </BrowserRouter>
    </UserStorage>
  );
}

export default App;

注意:所有调用useContext(UserContext)的组件必须是<UserStorage>的后代组件,超出范围的组件无法获取上下文。

3. 可选:给Context设置默认值(避免意外报错)

创建Context时传入默认值,即使组件不在Provider范围内,也不会直接返回undefined,方便调试:

export const UserContext = React.createContext({
  userLogin: () => {},
  data: null,
});

验证修复

完成以上步骤后:

  • 确认UserStorage无报错
  • 检查Header和LoginForm都在<UserStorage>子树中
  • 重新运行项目,报错应消失,登录后Header可正常显示用户邮箱

内容的提问来源于stack exchange,提问作者Nat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 18:52:49