Next.js App Router + MDX 项目中出现TypeError: createContext仅支持客户端组件的问题求助
大家好,我最近在跟着Next.js官方指南搭建Next.js + MDX的项目模板,用的是App Router,但访问/pg路由时直接报了500错误,具体错误信息如下:
⨯ TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component at webpack_require (.next/server/webpack-runtime.js:33:42) at eval (webpack-internal:///(rsc)/./app/pg/page.mdx:7:85) at
(rsc)/./app/pg/page.mdx (/home/baltej/Desktop/files/posts/.next/server/app/pg/page.js:33:1) at Function.webpack_require (.next/server/webpack-runtime.js:33:42) { page: '/pg' } GET /pg 500 in 501ms
我的项目完全基于App Router,下面是我的配置文件和项目结构:
next.config.js
import createMDX from '@next/mdx' /** @type {import('next').NextConfig} */ const nextConfig = { // Configure `pageExtensions` to include markdown and MDX files pageExtensions: ['js', 'jsx', 'md', 'mdx', 'ts', 'tsx'], // Optionally, add any other Next.js config below } const withMDX = createMDX({ // Add markdown plugins here, as desired }) // Merge MDX config with Next.js config export default withMDX(nextConfig)
项目目录结构
. ├── app │ ├── layout.js │ ├── md-components.js │ └── pg │ └── page.mdx ├── eslint.config.mjs ├── jsconfig.json ├── next.config.js ├── package.json ├── package-lock.json ├── public │ ├── file.svg │ ├── globe.svg │ ├── next.svg │ ├── vercel.svg │ └── window.svg └── README.md
我自己猜会不会是app/md-components.js这个自定义MDX组件文件的问题?毕竟App Router默认都是服务器组件,如果这个文件里用到了React Context这类客户端特性,没加'use client'指令的话就会报错?但我不太确定具体问题出在哪,有没有遇到过类似情况的朋友能帮我排查一下,或者给点排查方向呀?
内容来源于stack exchange

