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

Expo集成react-native-firebase报错:未创建默认Firebase应用

Expo集成react-native-firebase认证状态监听报错解决

问题描述

我通过Expo集成react-native-firebase模块,已按要求创建Firebase安卓/iOS应用,配置了google-services.json和GoogleService-Info.plist文件。参考官方文档添加认证状态变更监听器后,调用auth().onAuthStateChanged时出现错误:Error: No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp()。移除订阅后Expo开发应用可正常运行,但文档说明Expo环境下无需手动调用firebase.initializeApp(),需要解决这个问题以实现认证状态监听功能。

项目配置(app.json/app.config.js):

{
  "plugins": [
    "@react-native-firebase/app",
    "@react-native-firebase/auth",
    "@react-native-firebase/firestore",
    "@react-native-google-signin/google-signin",
    [
      "expo-build-properties",
      {
        "ios": {
          "useFrameworks": "static"
        }
      }
    ],
    [
      "expo-document-picker",
      {
        "iCloudContainerEnvironment": "Production"
      }
    ]
  ],
  "ios": {
    "googleServicesFile": "./GoogleService-Info.plist",
    "supportsTablet": true,
    "bundleIdentifier": "你的包名"
  },
  "android": {
    "googleServicesFile": "./google-services.json",
    "adaptiveIcon": {
      "foregroundImage": "./assets/adaptive-icon.png",
      "backgroundColor": "#ffffff"
    },
    "package": "你的包名"
  }
}

依赖版本:

{
  "@react-native-firebase/app": "20.5.0",
  "@react-native-firebase/auth": "20.5.0",
  "@react-native-firebase/firestore": "20.5.0",
  "@react-native-firebase/functions": "20.5.0",
  "@react-native-google-signin/google-signin": "^12.1.0"
}

入口文件监听代码:

const [initializing, setInitializing] = useState(true);
function onAuthStateChanged(user: any) {
  if (initializing) setInitializing(false);
}
useEffect(() => {
  const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
  return subscriber; // unsubscribe on unmount
}, []);

if (initializing) return null;

解决方案

1. 执行Expo预构建

react-native-firebase依赖原生项目配置,必须先执行预构建生成原生文件:

npx expo prebuild

如果之前执行过,建议清理后重新构建:

npx expo prebuild --clean

2. 清除开发服务器缓存

Expo热加载缓存可能导致初始化异常,重启服务器并清除缓存:

npx expo start --clear

3. 检查配置文件路径

确认google-services.json和GoogleService-Info.plist确实放在项目根目录,与配置中的./路径一致。如果文件在子文件夹,需修改配置中的路径(比如./assets/google-services.json)。

4. 验证版本兼容性

react-native-firebase 20.x对应Expo SDK 51,确保你的Expo SDK版本与依赖版本匹配。如果SDK版本不兼容,需调整react-native-firebase版本或升级Expo。

5. 临时排查:手动初始化测试(仅用于排查)

虽然文档说Expo下无需手动初始化,但可以临时添加初始化代码验证是否是初始化问题:

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

// 在组件挂载前或入口文件顶部添加
if (!firebase.apps.length) {
  firebase.initializeApp();
}

如果添加后报错消失,说明插件自动初始化未生效,需检查预构建和插件配置是否正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:28:09