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

使用MDXRemote时出现_jsxDev is not a function错误求助

排查Next.js + MDX博客中_jsxDev is not a function错误

我使用Next.js和MDX搭建博客,先完成了基于Next.js和Markdown的博客搭建流程,之后参考教程内容将Markdown切换为MDX,但<MDXRemote {...props.mdxSource} components={components} />这行代码触发了_jsxDev is not a function错误。以下是完整代码:

import fs from 'fs'
import matter from 'gray-matter'
import { serialize } from 'next-mdx-remote/serialize'
import { MDXRemote } from 'next-mdx-remote'

import path from 'path'

export default function Post(props) {
    const components = {}

    return (
        <>
            // 此行代码触发错误
            <MDXRemote {...props.mdxSource} components={components} />
        </>
    )
}

export async function getStaticProps(context) {    
    const markdownWithMeta = fs.readFileSync(
        path.join('posts', slug + '.mdx'),
        'utf-8'
    )
    const { content } = matter(markdownWithMeta)
    const mdxSource = await serialize(content)

    return {
        props: {            
            mdxSource,            
        },
    }
}

可能的解决方法:

  • 版本兼容性问题:next-mdx-remote版本与Next.js不匹配会引发这类错误。如果使用Next.js 12及以下版本,需将next-mdx-remote降级到v3版本,执行命令:

    npm install next-mdx-remote@3
    

    若使用Next.js 13+,确保next-mdx-remote为v4及以上版本。

  • 未定义的slug变量:getStaticProps中未从context获取slug参数,导致文件读取路径错误,修改代码如下:

    export async function getStaticProps(context) {    
        const { slug } = context.params; // 从context中获取slug参数
        const markdownWithMeta = fs.readFileSync(
            path.join('posts', `${slug}.mdx`),
            'utf-8'
        )
        const { content } = matter(markdownWithMeta)
        const mdxSource = await serialize(content)
    
        return {
            props: {            
                mdxSource,            
            },
        }
    }
    

    同时需补充getStaticPaths函数生成静态路径(Pages Router环境下):

    export async function getStaticPaths() {
        const files = fs.readdirSync(path.join('posts'))
        const paths = files.map(file => ({
            params: { slug: file.replace('.mdx', '') }
        }))
    
        return {
            paths,
            fallback: false
        }
    }
    
  • 缓存或依赖问题:删除Next.js缓存文件夹和本地依赖,重新安装后重启服务:

    rm -rf .next node_modules package-lock.json
    npm install
    npm run dev
    
  • MDXRemote使用验证:确保serialize函数正确处理MDX内容,若MDX文件包含自定义组件,需在components对象中注册对应组件(当前代码中components为空,若MDX无自定义组件可忽略)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:10:38