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

Next.js TypeError问题:自定义_document类继承报错求助

解决Next.js自定义_document类组件时的TypeError问题

错误原因分析

这个报错通常有两种核心诱因:

  • 路由模式/版本不兼容:Next.js 13+推出的App Router(app/目录)完全不支持类组件形式的_document,仅允许使用函数式组件。如果你的项目基于App Router架构,强行编写类组件继承Document会触发该错误——因为此时Document并非可被继承的构造函数。
  • 导入方式错误:在Pages Router(pages/目录)中,Document是next/document的默认导出,若误用命名导入(比如import { Document } from 'next/document'),会导致你继承的不是合法的构造函数,进而抛出错误。

对应解决方案

情况1:项目使用App Router(app/目录)

放弃类组件写法,严格遵循App Router的_document规范,使用函数式组件:

import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html lang="zh-CN">
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

若需自定义类似renderPage的逻辑,可通过generateMetadata、中间件或路由组配置实现全局逻辑处理。

情况2:项目使用Pages Router(pages/目录)

修正导入方式,确保正确继承默认导出的Document,同时遵循类组件的写法规范:

// 正确导入:默认导出
import Document from 'next/document'
import { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    // 自定义renderPage逻辑
    const originalRenderPage = ctx.renderPage
    ctx.renderPage = () =>
      originalRenderPage({
        enhanceApp: (App) => (props) => <App {...props} />
      })
    return { ...initialProps }
  }

  render() {
    return (
      <Html lang="zh-CN">
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

注意:Pages Router中_document必须放在pages/_document.js(或.tsx)文件中,且仅用于自定义全局HTML结构,不能处理客户端交互逻辑。

额外排查点

  • 检查next版本:运行npm list next确认版本,13+若使用App Router则无法使用类组件_document。
  • 确认文件路径:_document文件必须放在pages/或app/根目录,不能嵌套子目录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:35:22