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

react-beautiful-dnd移除节点报错求助:非子节点无法执行removeChild

临时修复Gatsby + react-beautiful-dnd路由切换时的removeChild错误

在Gatsby项目里使用react-beautiful-dnd,每次离开对应页面都会抛出以下错误:

Error in function remove in ./node_modules/react-beautiful-dnd/dist/react-beautiful-dnd.esm.js:5017
Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

根源是Gatsby的路由卸载逻辑和react-beautiful-dnd的DOM节点清理逻辑冲突,这里给几个临时修复方案:

  • 手动在组件卸载前清理DOM节点
    利用React的useEffect清理函数,在组件卸载前检查并移除react-beautiful-dnd挂载到head的节点:

    import { useEffect, useRef } from 'react';
    import { DragDropContext } from 'react-beautiful-dnd';
    
    const YourDraggableComponent = () => {
      const dndContextRef = useRef(null);
    
      useEffect(() => {
        return () => {
          if (dndContextRef.current) {
            const head = document.head;
            const dndNode = dndContextRef.current;
            if (head.contains(dndNode)) {
              head.removeChild(dndNode);
            }
          }
        };
      }, []);
    
      return (
        <DragDropContext ref={dndContextRef} {/* 你的其他配置props */}>
          {/* 你的拖拽列表/组件内容 */}
        </DragDropContext>
      );
    };
    
  • 给react-beautiful-dnd打补丁(持久化修改)
    找到node_modules/react-beautiful-dnd/dist/react-beautiful-dnd.esm.js里报错的remove函数,在执行removeChild前先判断节点是否属于head的子节点:

    // 替换原5017行代码
    const head = getHead();
    if (head.contains(current)) {
      head.removeChild(current);
    }
    

    然后用patch-package把这个修改做成持久化补丁:

    1. 安装依赖:npm install patch-package --save-dev
    2. 运行命令生成补丁:npx patch-package react-beautiful-dnd
    3. 把项目根目录生成的patches文件夹提交到版本控制,后续安装依赖会自动应用补丁
  • 用Suspense延迟组件卸载
    在拖拽页面的路由外层包裹Suspense,给react-beautiful-dnd足够时间完成DOM清理:

    import { Suspense } from 'react';
    import { Route } from '@gatsbyjs/reach-router';
    import DraggablePage from './DraggablePage';
    
    const AppRoutes = () => (
      <Route
        path="/your-draggable-page"
        element={
          <Suspense fallback={<div>加载中...</div>}>
            <DraggablePage />
          </Suspense>
        }
      />
    );
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:24:55