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

React Native报错TypeError: null is not an object (evaluating 'modalSuccess.open')原因排查

你遇到的TypeError: null is not an object (evaluating 'modalSuccess.open')报错,核心原因是调用open方法时,modalSuccess还未被正确赋值为Modal组件的实例,仍为初始的null值,具体错误点和修复方案如下:

错误原因

  • useRef用法错误:你直接在声明时提取了useRef(null).current赋值给普通变量modalSuccess,组件首次执行时Modal还没挂载,此时current就是null,而且普通变量不会跟随ref的更新同步刷新值,就算后续Modal挂载完成ref更新了,你之前声明的modalSuccess变量还是初始的null。
  • 缺少非空校验:useEffect触发时,可能Portal包裹的Modal组件还未完成挂载,ref还没被赋值为组件实例,直接调用方法就会报错。

修复方案

步骤1:修正ref声明

将代码中

let modalSuccess = useRef(null).current;

修改为

const modalSuccessRef = useRef(null);

保留完整的ref对象,后续通过modalSuccessRef.current访问组件实例。

步骤2:修正Modal组件的ref绑定

将JSX中的

<ModalCollectionSuccess ref={el => (modalSuccess = el)} />

修改为

<ModalCollectionSuccess ref={modalSuccessRef} />

直接把ref对象传递给组件的ref属性即可。

步骤3:给useEffect里的方法调用加非空校验

将useEffect代码修改为:

useEffect(() => {
  // 先判断组件实例存在再调用open方法
  if (user.showCollectionSuccess === true && modalSuccessRef.current) {
    modalSuccessRef.current.open();
  }
}, [user.showCollectionSuccess]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:45:04