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

Next.js中使用Lexical构建报错:MutationObserver参数非Node类型

问题

在Next.js中使用Lexical编辑器(版本^0.16.0),执行npm run dev时所有功能正常,但运行npm run build时出现以下错误:

TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
at oo (6506-58498e6309b8c34d.js:1:128656)
at Po.setRootElement (6506-58498e6309b8c34d.js:1:150077)
...

对应的Lexical组件代码如下:

import { $getRoot } from "lexical";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { LexicalComposer } from "@lexical/react/LexicalComposer";
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
import MyLexicalTheme from "../lexical-theme";
import ToolbarPlugin from "./ToobarPlugin";
import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";
import { $generateHtmlFromNodes } from "@lexical/html";
import { useEffect } from "react";

const theme = MyLexicalTheme;

function onError(error) {
  throw error;
}

function LexicalEditorWrapper({
  setMyCommentText,
  setEditorAndRootValuesInParent,
}) {
  const initialConfig = {
    namespace: "MyEditor",
    theme,
    onError,
  };
  return (
    <LexicalComposer initialConfig={initialConfig}>
      <div className="editor-container">
        <div className="editor-inner">
          <RichTextPlugin
            contentEditable={<ContentEditable className="editor-input" />}
            placeholder={
              <div className="editor-placeholder">Enter some text...</div>
            }
          />
        </div>
      </div>
    </LexicalComposer>
  );
}

export default LexicalEditorWrapper;
解决方案

这个错误的核心原因是Lexical编辑器依赖浏览器环境的DOM API,而Next.js构建时的SSR/SSG阶段没有可用的DOM节点,导致MutationObserver无法正常初始化。具体解决步骤如下:

  • App Router场景:标记为客户端组件
    在LexicalEditorWrapper文件顶部添加'use client'指令,强制组件仅在客户端渲染:

    'use client'; // 新增该行
    import { $getRoot } from "lexical";
    // 其余导入代码保持不变
    
  • Pages Router场景:动态导入并禁用SSR
    在引用编辑器的页面中,使用Next.js的dynamic方法导入组件,并关闭SSR:

    import dynamic from 'next/dynamic';
    
    const LexicalEditorWrapper = dynamic(() => import('./path/to/LexicalEditorWrapper'), {
      ssr: false,
      loading: () => <div>加载编辑器中...</div>
    });
    
  • 确保DOM相关逻辑仅在客户端执行
    如果有自定义逻辑依赖DOM节点,用useEffect包裹,确保只在组件客户端挂载后执行:

    useEffect(() => {
      // 此处放置需要DOM的逻辑,比如获取编辑器实例、监听内容变化等
    }, []);
    
  • 可选:升级Lexical版本
    后续Lexical版本对Next.js的SSR兼容性有优化,可考虑升级到最新稳定版:

    npm install lexical@latest @lexical/react@latest
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 13:26:14