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

Next.js中读取Firebase实时数据报错:ref.on is not a function

解决Firebase实时数据库on方法报错"reference.on is not a function"的问题

这个错误的核心原因是Firebase v9+采用了模块化API设计,你虽然正确导入了on函数,但调用方式还停留在v8的对象方法模式(reference.on(...)),而v9中on是独立的顶层函数,需要把数据库引用作为第一个参数传入。

修正后的代码

import { getDatabase, ref, set, once, on, update, onChildAdded } from 'firebase/database';

const reference = ref(db, 'room/new');
  
// 正确的实时数据监听写法
on(reference, 'value', (snapshot) => {
    console.log("In Value");
    console.log(snapshot.val());
}, (error) => {
    console.error(error);
});

额外注意点

所有Firebase实时数据库的监听类函数(比如onChildAdded、onChildChanged等)都要遵循这个函数式调用规则,不能再用reference.onXXX(...)的形式,比如:

// 正确的onChildAdded调用方式
on(reference, 'child_added', (snapshot) => {
    console.log('新增子节点:', snapshot.val());
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:20:46