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

Next.js 13使用useContext报错及类型问题求助:如何修复?

错误分析与修复方案

错误1:useContext参数类型不匹配

你在page.tsx里犯了核心错误:把Context Provider组件传给了useContext,但useContext要求的参数是createContext创建的Context对象,不是Provider组件。这直接触发了类型错误:Argument of type '({ children }: { children: any; }) => Element' is not assignable to parameter of type 'Context<unknown>'。

错误2:children参数缺少类型声明

store.tsx里的GlobalContextProvider组件的children参数未指定类型,TypeScript默认推断为any,因此出现提示:(parameter) children: any Binding element 'children' implicitly has an 'any' type.。

额外隐患:Context默认值类型不匹配

创建GlobalContext时,默认的setUserId和setData函数返回了值,但Dispatch<SetStateAction<T>>类型的函数不需要返回值(返回void),这会导致类型隐患。


修复后的完整代码

1. 修改Context/store.tsx

'use client';

import { createContext, Dispatch, SetStateAction, useState, ReactNode } from "react";

interface ContextProps {
    userId: string,
    setUserId: Dispatch<SetStateAction<string>>,
    data: object[],
    setData: Dispatch<SetStateAction<object[]>>
}

// 修正默认值的函数类型:Dispatch不需要返回值
const GlobalContext = createContext<ContextProps>({
    userId: '',
    setUserId: () => {},
    data: [],
    setData: () => {} 
})

// 给children指定ReactNode类型
export const GlobalContextProvider = ({ children }: { children: ReactNode }) => {
    const [userId, setUserId] = useState('');
    // useState类型简化为object[]即可,无需写[] | object[]
    const [data, setData] = useState<object[]>([]);
    
    return (
        <GlobalContext.Provider value={{ userId, setUserId, data, setData }}>
            {children}
        </GlobalContext.Provider>
    )
};

// 同时导出Context对象和Provider组件
export default GlobalContextProvider;
export { GlobalContext };

2. 修改page.tsx

'use client';

import { useContext, useEffect } from 'react';
// 导入GlobalContext而非GlobalContextProvider
import { GlobalContext } from './Context/store';
import styles from './page.module.css';

export default function Home() {
    // 用GlobalContext作为useContext的参数
    const { userId, setUserId } = useContext(GlobalContext);

    return (
        <div className={styles.container}>
            
        </div>
    )
}

关键修复点总结

  • useContext必须接收createContext创建的Context对象,不能传Provider组件。
  • 给组件的children参数显式指定React.ReactNode类型,避免TypeScript推断为any。
  • 确保Context默认值的类型与ContextProps完全匹配,Dispatch函数不需要返回值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:15:28