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

React中出现Cannot read property 'removeEventListener' of null错误求助

解决React中Cannot read properties of null (reading 'removeEventListener')错误

你的代码里有三个核心问题导致了这个错误:

  • 清理函数执行时ref已为null:组件卸载时,props.containerRef.current可能已经被置为null,直接调用removeEventListener会触发null报错。
  • 事件处理函数未缓存:handleComponentClick定义在组件内部,每次渲染都会生成新的函数实例,导致绑定和解绑的不是同一个函数,不仅解绑无效,还会引发额外问题。
  • useEffect无依赖数组:未指定依赖的useEffect会在每次组件渲染时重复执行,频繁绑定/解绑事件,增加出错概率。

修复方案

  1. 用useCallback缓存事件处理函数,保证函数引用稳定
  2. 给useEffect添加依赖数组,精准控制执行时机
  3. 在清理函数中先判断ref的current是否存在,再执行解绑操作

修复后的代码

const CompA = () => {
  let containerRef = React.useRef(null);
  return (
    <div ref={containerRef}>
      <CompB containerRef={containerRef} />
    </div>
  );
}

const CompB = (props) => {
  return <CompC containerRef={props.containerRef} />;
}

const CompC = (props) => {
  // 用useCallback缓存处理函数,确保引用不变
  const handleComponentClick = React.useCallback(() => {
    alert("Component clicked");
  }, []);

  React.useEffect(() => {
    const container = props.containerRef.current;
    // 先判断容器是否存在再绑定事件
    if (container) {
      container.addEventListener("click", handleComponentClick);
    }

    return () => {
      // 清理时同样先判断容器是否存在
      if (container) {
        container.removeEventListener("click", handleComponentClick);
      }
    };
  }, [props.containerRef, handleComponentClick]); // 添加依赖数组

  return "test";
}

额外说明

  • useCallback的依赖数组为空,因为handleComponentClick内部没有依赖外部变量;如果后续有依赖,需要把对应的变量加入依赖数组。
  • useEffect的依赖数组包含props.containerRef和handleComponentClick,确保只有当这两个值变化时才重新执行绑定逻辑。
  • 提前将props.containerRef.current赋值给局部变量,避免清理函数执行时ref的current已变为null的情况(闭包会捕获当前值)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:36:23