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

React Native Expo+Firebase9实时数据库无法用off()取消onValue监听问题

解决方案

Firebase 9 采用模块化API设计,废弃了原有命名空间版本中绑定在Reference实例上的off()、removeEventListener()等实例方法,你遇到的方法不存在报错是版本API差异导致的。

方案1:使用监听函数返回的卸载方法(最简便)

onValue() 调用后会直接返回一个可执行的取消订阅函数,你只需要保存该函数,在useEffect清理阶段调用即可:

import { getDatabase, ref, onValue } from "firebase/database";

const db = getDatabase();
const reference = ref(db, "users/" + props.userId);

const updateScore = (snapshot) => {
  // 注:原代码此处逻辑存在疏漏,需先从快照中取值再赋值
  const highscore = snapshot.val();
  if (highscore !== null) setHighScore(highscore);
};

useEffect(() => {
  if (props.userId === "") {
    props.navigation.navigate("Auth");
    return;
  }
  // 保存onValue返回的卸载函数
  const unsubscribe = onValue(reference, updateScore);
  
  // 清理阶段直接调用卸载函数
  return () => unsubscribe();
}, [props.userId]);

方案2:使用独立导入的off方法

如果你需要手动指定事件类型、回调来移除监听,也可以从firebase/database包中导入独立的off函数调用:

import { getDatabase, ref, onValue, off } from "firebase/database";

// 其余业务代码不变

useEffect(() => {
  if (props.userId === "") {
    props.navigation.navigate("Auth");
    return;
  }
  onValue(reference, updateScore);
  
  // 清理阶段调用导入的off函数,依次传入引用、事件类型、对应回调
  return () => off(reference, 'value', updateScore);
}, [props.userId]);

内容的提问来源于stack exchange,提问作者Thomas W. Smith

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:54:04