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

NextJS Pages目录下useContext导致静态导出失败问题求助

Next.js静态导出时Pages目录组件使用useContext报错问题

我在Next.js 13.4.7项目中遇到以下问题:npm run dev运行正常,但执行next build进行静态导出时出错。通过最小复现案例验证,问题根源在于Pages目录下的文件导入了使用useContext的组件,在导出阶段的- info Collecting page data [ ] - info Generating static pages (0/5)环节抛出错误。

测试场景

  • 将ComponentA直接放在app目录的page.js中、不导入到Pages目录的initial.js时,可正常导出
  • 不把ComponentA放入Pages目录的initial.js时,可正常导出
  • 将ComponentA放入Pages目录的initial.js时,导出失败
  • 注释ComponentA中的const {state , dispatch} = useContext(MyContext)语句,再放入initial.js时,可正常导出

相关代码

componentA.js

"use client"
import React, { Fragment, useContext } from 'react'
import { MyContext } from './mycontext'

export default function ComponentA() {
    const {state , dispatch} =  useContext(MyContext)

    return(
        <Fragment>A</Fragment>
    )
}

initial.js(Pages目录下)

"use client"
import React from 'react'
import ComponentA from "../src/app/componentA"

export default function Initial() {
  return (
    <div>
      <ComponentA></ComponentA>
    </div>
  )
}

mycontext.js

import React, { createContext, useReducer, useEffect } from "react";
import { MyReducer } from "./myreducer";

export const MyContext = createContext();

const MyContextProvider = (props) => {
  const [state, dispatch] = useReducer(MyReducer, [], () => {
    if (typeof window !== 'undefined') {
      const localData = localStorage.getItem("state");
      return localData ? JSON.parse(localData) : [];
    }
    return [];
  });

  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem("state",JSON.stringify(state))
    }
  }, [state]);

  return (
    <MyContext.Provider value={{ state, dispatch }}>
      {props.children}
    </MyContext.Provider>
  );
};

export default MyContextProvider;

myreducer.js

export const MyReducer = (state, action) => {
  switch (action.type) {
    case "ADD":
      return [...state,{...action}];
    default: 
      return state;
  }
};

app/page.js

"use client"
import MyContextProvider from './mycontext'
import { Fragment } from 'react'
import Initial from '../../pages/initial'

export default function Home() {
  return (
    <Fragment>
      <MyContextProvider>
        <Initial></Initial>
      </MyContextProvider>
    </Fragment>
  )
}

next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
    images: {
        unoptimized: true,
      },
      output: 'export'
  }

module.exports = nextConfig

package.json

{
  "name": "minimumviable",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "13.4.7",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  }
}

报错信息

Error occurred prerendering page "/initial". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: Cannot destructure property 'state' of '(0 , external_react_.useContext)(...)' as it is undefined.
at ComponentA

大型项目中报错核心一致,都是无法读取undefined的state属性,追踪到生成代码中_useContext.state行出错。

已尝试的方法

  • 重命名state变量
  • 直接调用React.useContext而非解构导入
  • 尝试将useContext放入条件语句(但React不允许这种用法)

以上方法均未解决问题,由于项目需要使用动态路由必须依赖Pages目录,想知道Next.js Pages目录中使用useContext是否需要特殊配置,以及如何解决该静态导出报错问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 14:55:06