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

添加Firebase Auth持久化致Expo崩溃:无默认Firebase应用

问题描述

在为Firebase Auth添加持久化功能时,Expo应用在iOS模拟器中出现崩溃问题。移除initializeAuth中的持久化配置后应用可正常运行,但持久化是避免用户每次启动应用都需重新登录的必要功能。

报错信息

ERROR  FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
ERROR  Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.

现有代码

import {
    FirebaseApp,
    FirebaseOptions,
    getApp,
    getApps,
    initializeApp,
} from 'firebase/app';

import {
    initializeAuth,
    getReactNativePersistence,
    Auth,
    getAuth,
} from 'firebase/auth/react-native';

import Constants from 'expo-constants';
import AsyncStorage from '@react-native-async-storage/async-storage';

const firebaseConfig: FirebaseOptions = {
    apiKey: Constants.manifest.extra.firebase.apiKey as string,
    authDomain: Constants.manifest.extra.firebase.authDomain as string,
    projectId: Constants.manifest.extra.firebase.projectId as string,
    storageBucket: Constants.manifest.extra.firebase.storageBucket as string,
    messagingSenderId: Constants.manifest.extra.firebase
        .messagingSenderId as string,
    appId: Constants.manifest.extra.firebase.appId as string,
    databaseURL: Constants.manifest.extra.firebase.databaseURL as string,
};

const app: FirebaseApp =
    getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();

const auth: Auth =
    getApps().length === 0
        ? initializeAuth(app, {
                persistence: getReactNativePersistence(AsyncStorage),
          })
        : getAuth(app);


export {app, auth};
解决方案

问题出在Auth实例的初始化逻辑上:通过getApps().length判断是否初始化带持久化的Auth,当Firebase App已存在时,直接调用getAuth(app)会创建使用默认内存持久化的Auth实例,与预期配置冲突,同时可能引发App未找到的错误。

修改Auth初始化部分的代码为:

const app: FirebaseApp = getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();

let auth: Auth;
try {
  // 尝试获取已初始化的Auth实例
  auth = getAuth(app);
} catch {
  // 若Auth未初始化,则配置持久化后初始化
  auth = initializeAuth(app, {
    persistence: getReactNativePersistence(AsyncStorage),
  });
}

补充说明

  • 该逻辑确保无论Firebase App是否已存在,都能正确初始化带AsyncStorage持久化的Auth实例
  • 避免了因判断条件错误导致的Auth实例不匹配问题
  • 确认已安装依赖:@react-native-async-storage/async-storage及所有Firebase相关包,且Expo项目中Constants.manifest.extra的Firebase配置正确

内容的提问来源于stack exchange,提问作者Joel Sandén

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:21:58