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

React useRef报错:null is not an object (evaluating 'dispatcher.useRef')求助

报错排查:null is not an object (evaluating 'dispatcher.useRef')

问题详情

遇到错误:null is not an object (evaluating 'dispatcher.useRef'),已尝试删除node_modules重装依赖、重写代码及调整useRef使用方式,问题仍未解决。

相关代码片段

useRef调用部分

const flatListRef = React.useRef();
const scrollX = React.useRef(new Animated.Value(0)).current;

const onViewChangeRef = React.useRef(({viewableItems, changed}) => {

视图渲染部分

<View
  style={{
    flex: 1,
    justifyContent: 'center',
  }}>
  {index == 0 && <Walkthrough1 />}
  {index == 1 && <Walkthrough2 animate={walkthrough2Animate || false} />}
  {index == 2 && <Walkthrough3 animate={walkthrough3Animate} />}
  {index == 3 && <Walkthrough4 animate={walkthrough4Animate} />}
</View>

解决方案

1. 校验React版本兼容性

该报错多因版本不匹配导致:

  • 查看package.json中react与react-native(若为RN项目)的版本,确保二者适配(比如RN 0.65+对应React 17.x,0.68+对应React 18.x)。
  • 执行npm list react或yarn list react检查是否存在多版本React嵌套依赖,若有,删除package-lock.json/yarn.lock后重装,或在package.json中通过overrides(npm)、resolutions(yarn)强制统一版本。

2. 确保Hooks调用规范

useRef必须在函数组件顶层调用,不能放在循环、条件判断或嵌套函数内。检查你的useRef是否违反了这个规则。

3. 排查Animated库兼容性

测试简化scrollX的定义,排除Animated库的问题:

const scrollX = React.useRef(0).current;

若此写法不报错,再针对性排查Animated.Value的版本适配或使用方式问题。

4. 检查自定义组件导出

确认Walkthrough1等组件是标准的函数/类组件,未导出非组件对象导致React上下文识别异常。

5. 清除全量缓存

除删除node_modules外,补充执行:

  • RN项目:npx react-native start --reset-cache
  • npm/yarn缓存:npm cache clean --force 或 yarn cache clean

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:50:26