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

如何读取Firebase Realtime Database?ref.on不是函数报错如何解决

Firebase Realtime Database 读取报错问题排查

核心错误原因

  • 变量命名冲突:你从firebase/database导入了工具函数ref,同时将创建的数据库引用实例命名为ref,导致命名覆盖,后续调用逻辑异常。
  • API写法不匹配:你使用的是Firebase v9+ 模块化SDK,该版本已将事件监听方法从ref实例上剥离,不存在ref.on()的用法,相关方法需要单独导入使用。

修复方案

第一步:调整导入语句

新增导入onValue方法,对应原来的on('value')监听逻辑:

import { initializeApp } from "firebase/app";
import { getDatabase, ref, push, set, onValue } from "firebase/database";

第二步:调整业务代码

修改变量名避免冲突,使用导入的onValue方法绑定监听:

function readpixels() {
  const db = getDatabase();
  const pixelRef = ref(db, 'pixels');
  onValue(pixelRef, (snapshot) => {
    // snapshot.val() 可获取对应节点的全部数据
    console.log("read", snapshot.val())
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:54:07