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

React TypeScript中createContext报错:找不到StateContext命名空间

解决TypeScript下React createContext报错“Cannot find namespace 'StateContext'”

错误原因及解决方案

1. 直接引用未导出的StateContext

你的代码中StateContext是内部声明的变量,没有对外导出。如果其他组件尝试直接导入StateContext(比如import { StateContext } from './xxx'),TypeScript就会抛出“找不到命名空间”的错误。

解决方式:

  • 优先使用你定义的useStateContext自定义Hook访问上下文(封装性更好),避免在外部直接引用StateContext;
  • 若确实需要直接使用StateContext(比如StateContext.Consumer),为其添加导出:
export const StateContext = React.createContext<StateContextType>({
  address: null,
  contract: undefined,
  connect: () => {},
  createNewProfile: () => Promise.resolve(),
});

2. 文件扩展名错误

确保上下文文件使用.tsx扩展名,而非.ts。因为文件包含JSX代码(<StateContext.Provider />),.ts文件不支持JSX语法,会导致TypeScript无法正确识别React相关变量和类型。

3. TypeScript配置缺失React支持

检查tsconfig.json配置:

  • 确保jsx选项设置为react-jsx(React 17+)或react:
{
  "compilerOptions": {
    "jsx": "react-jsx",
    // 其他配置项...
  }
}
  • 确保已安装@types/react依赖:
npm install @types/react --save-dev
# 或
yarn add @types/react --dev

额外代码修正(预防功能异常)

虽然不是当前报错的原因,但你的代码存在两个会导致功能失效的问题:

  1. StateContext.Provider未传递value
    必须将上下文的实际状态和方法传递给Provider,否则useStateContext拿到的始终是初始默认值:
return (
  <StateContext.Provider
    value={{
      address: address ?? null, // 将undefined转换为null,匹配StateContextType定义
      contract,
      connect,
      createNewProfile: createNewProfileRequest,
    }}
  >
    {children}
  </StateContext.Provider>
);
  1. useAddress()返回值类型不匹配
    useAddress()返回值为string | undefined,但StateContextType中address定义为string | null,可通过address ?? null转换类型,或调整StateContextType的定义:
type StateContextType = {
  address: string | null | undefined;
  // 其他属性...
};

内容的提问来源于stack exchange,提问作者Jan Cahlík

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:17:11