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

React Native Firebase实时数据库报错:Undefined is not a function

问题:React Native Firebase实时数据库调用报错this._database.native.once is not a function

问题背景

  • 基于Expo搭建的React Native项目
  • 使用React Native Firebase 16.5.0版本,其他Firebase包可正常运行
  • 已按官方指南完成配置,数据库规则设为公开读写
  • 调用代码:
database()
  .ref('/users/123')
  .once('value')
  .then((snapshot) => {
      console.log('User data: ', snapshot.val());
  });
  • 数据库结构:
{
  "users": {
    "123": ""
  }
}

报错信息

TypeError: this._database.native.once is not a function. (In 'this._database.native.once(this.path, modifiers, eventType)', 'this._database.native.once' is undefined)

VS Code智能提示:

database(app?: ReactNativeFirebase.FirebaseApp | undefined): FirebaseDatabaseTypes.Module
import database


原因分析

该错误核心原因是Expo托管环境下,React Native Firebase实时数据库模块未正确安装或初始化——Expo的沙箱环境对原生依赖有特殊要求,部分RN Firebase模块需要额外配置才能正常工作。

解决步骤

1. 确认实时数据库包已正确安装

确保项目中已安装对应版本的@react-native-firebase/database,版本需与其他RN Firebase包保持一致(16.5.0):

npm install @react-native-firebase/database@16.5.0
# 或使用yarn
yarn add @react-native-firebase/database@16.5.0

2. 重置Expo缓存并重启项目

Expo缓存可能导致依赖未正确加载,执行以下命令清除缓存后重启:

expo start --clear

如果是预构建的Expo项目,需重新执行预构建:

expo prebuild --clean

3. 检查Firebase初始化配置

确保项目入口文件(如App.js)中已正确初始化Firebase,且指定了数据库URL(部分场景下需显式配置):

import firebase from '@react-native-firebase/app';

const firebaseConfig = {
  // 你的Firebase项目配置
};

// 初始化时显式指定数据库URL
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig, {
    databaseURL: 'https://你的项目ID.firebaseio.com'
  });
}

4. 临时替换API测试

用on监听方法替代once测试,验证模块是否能正常工作:

const unsubscribe = database()
  .ref('/users/123')
  .on('value', snapshot => {
    console.log('User data: ', snapshot.val());
    unsubscribe(); // 仅监听一次
  });

5. 调整RN Firebase版本

若上述方法无效,16.5.0版本可能存在Expo兼容问题,尝试切换到同系列稳定版本(如16.4.0)或升级到最新兼容Expo的版本。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:55:18