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

在TypeScript中使用React Context API遇类型错误求助

解决TypeScript中React Context的"only refers to a type, but is being used as a namespace here"错误

错误根源

你在调整createContext代码时,把泛型参数写成了CounterContext——但这个是你用createContext创建的实例变量,不是类型。TypeScript要求泛型位置必须传入类型(也就是你定义的CounterContextType),把变量当类型用自然会触发这个报错。

修复步骤

  1. 修正泛型参数
    把错误的泛型写法改回正确的类型引用:

    // 正确写法:用定义好的CounterContextType类型
    export const CounterContext = createContext<CounterContextType | null>(null);
    

    你之前误写成createContext<CounterContext | null>(null),这才是问题核心,改文件后缀(.ts/.tsx)或者加React.前缀都解决不了这个类型混淆的问题。

  2. 确认Provider和Hook的使用逻辑
    你的Provider和自定义Hook逻辑本身是没问题的,只要确保:

    • 所有需要访问上下文的组件都被CounterContextProvider包裹
    • 不会在CounterContextProvider范围之外调用useCounterContext

完整修正后的代码

import React, { createContext, useContext, useState } from 'react';

type CounterContextProviderProps = {
    children: React.ReactNode;
};

type CounterContextType = {
    counter: number;
    setCounter: React.Dispatch<React.SetStateAction<number>>;
};

// 泛型参数使用CounterContextType类型,而非CounterContext变量
export const CounterContext = createContext<CounterContextType | null>(null);

const CounterContextProvider = ({ children }: CounterContextProviderProps) => {
    const [counter, setCounter] = useState(0);

    return (
        <CounterContext.Provider
            value={{
                counter,
                setCounter
            }}
        >
            {children}
        </CounterContext.Provider>
    );
}

export default CounterContextProvider;

export const useCounterContext = () => {
    const context = useContext(CounterContext);
    if (!context) {
        throw new Error('useCounterContext must be used within a CounterContextProvider');
    }
    return context;
};

额外优化提示

如果你不想在泛型里写| null,可以给Context一个默认的空实现,这样就不用在Hook里做null判断了:

export const CounterContext = createContext<CounterContextType>({
    counter: 0,
    setCounter: () => {}
});

注意默认值的行为要符合你的业务需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:58:23