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

React-Native-Firebase(v6) Firestore获取数据报错:undefined is not a function

解决React Native Firebase Firestore Android端的TypeError问题

我之前也踩过这个坑,这个错误一般是Firebase核心模块没初始化或者依赖配置不到位导致的,咱们一步步来解决:

1. 先确保Firebase核心App模块已安装并初始化

你只导入了Firestore模块,但react-native-firebase需要先初始化核心的App模块才能正常使用其他服务:

  • 先安装核心包:
    npm install @react-native-firebase/app
    # 或者用yarn
    yarn add @react-native-firebase/app
    
  • 从Firebase控制台下载你的google-services.json,放到android/app目录下
  • 在项目入口文件(比如index.js)初始化Firebase(如果还没做的话):
    import firebase from '@react-native-firebase/app';
    
    const firebaseConfig = {
      // 你的Firebase配置信息,从控制台获取
      apiKey: "YOUR_API_KEY",
      authDomain: "YOUR_AUTH_DOMAIN",
      projectId: "YOUR_PROJECT_ID",
      storageBucket: "YOUR_STORAGE_BUCKET",
      messagingSenderId: "YOUR_SENDER_ID",
      appId: "YOUR_APP_ID"
    };
    
    if (!firebase.apps.length) {
      firebase.initializeApp(firebaseConfig);
    }
    

2. 修正Firestore的导入方式

你当前的导入方式有问题,正确的导入应该从核心App模块或者直接导入Firestore模块:

  • 方式一:直接导入Firestore模块
    import firestore from '@react-native-firebase/firestore';
    // 然后使用
    await firestore().collection('Gyms').get();
    
  • 方式二:从核心App模块导入firebase
    import firebase from '@react-native-firebase/app';
    // 然后使用
    await firebase.firestore().collection('Gyms').get();
    

3. 检查Android项目的Gradle配置

确保你的Android项目配置正确:

  • 在android/build.gradle的dependencies块中添加Google Services插件:
    dependencies {
      // 其他依赖
      classpath 'com.google.gms:google-services:4.3.15' // 可以用最新版本
    }
    
  • 在android/app/build.gradle的末尾添加:
    apply plugin: 'com.google.gms.google-services'
    
  • 清理Android缓存,避免旧配置干扰:
    cd android && ./gradlew clean
    
    然后重新运行你的React Native项目。

4. 调整数据获取的时机

你在constructor里直接调用了getData(),这时候组件还没完成挂载,虽然是异步调用,但最好把数据获取逻辑放到componentDidMount生命周期里,避免潜在的初始化问题:

componentDidMount() {
  this.getData();
}

修正后的完整代码示例

import React, { Component } from 'react';
import firebase from '@react-native-firebase/app';
import firestore from '@react-native-firebase/firestore';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.getData = this.getData.bind(this);
    this.state = {};
  }

  componentDidMount() {
    this.getData();
  }

  async getData() {
    try {
      const querySnapshot = await firestore()
        .collection('Gyms')
        .get();
      console.log('Documents', querySnapshot.docs);
    } catch (e) {
      console.log('Error fetching data:', e);
    }
  }

  render() {
    return (
      // 这里放你的组件UI内容
      <></>
    );
  }
}

按照上面的步骤一步步排查,应该就能解决这个错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:49:55