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

Expo SDK 48升级后Expo Go中Firebase Auth持久化失效求助

问题分析与解决方案

核心问题

升级Expo SDK至v48后,Firebase Auth在Expo Go中丢失持久化特性,同时对多文件中getAuth()的使用方式存疑。

解决方案步骤

1. 修正Firebase初始化配置,统一Auth实例

你的ConfigFirebase.js仅初始化了Firebase App,未配置Auth持久化,也未导出可复用的Auth实例。修改如下:

import { initializeApp } from 'firebase/app';
import { getAuth, initializeAuth, getReactNativePersistence } from 'firebase/auth';
import AsyncStorage from '@react-native-async-storage/async-storage';

const firebaseConfig = {
  apiKey: "xxx",
  authDomain: "xxx",
  projectId: "xxx",
  storageBucket: "xxx",
  messagingSenderId: "xxx",
  appId: "xxx",
  databaseURL: "xxx",
  measurementId: "xxx"
};

// 初始化Firebase App
const app = initializeApp(firebaseConfig);

// 配置Auth持久化,指定AsyncStorage作为存储层(适配Expo Go环境)
const auth = initializeAuth(app, {
  persistence: getReactNativePersistence(AsyncStorage)
});

// 导出Auth实例供全项目复用
export { auth };

2. 调整App.js中的Auth使用逻辑

不再直接调用getAuth(),改为导入配置好的统一Auth实例,同时修复逻辑细节:

import React, { useState, useEffect } from 'react';
import { auth } from './src/config/ConfigFirebase'; // 导入统一Auth实例
import { onAuthStateChanged } from 'firebase/auth';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Purchases from 'react-native-purchases'; // 确保导入Purchases

const App = () => {
  const [isLogged, setIsLogged] = useState(false);
  const [loaded, setLoaded] = useState(false); // 补充缺失的loaded状态定义

  useEffect(() => {
    // 订阅Auth状态变化,返回取消订阅函数
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      if (user !== null) {
        Purchases.setAttributes({ "email": user.email, "displayName": user.displayName });
        setIsLogged(true);
      } else {
        setIsLogged(false);
      }
      setLoaded(true);
    });

    // 组件卸载时取消订阅,避免内存泄漏
    return unsubscribe;
  }, []);

  // Rest of code....

  if (!loaded) {
    return null; // 或自定义加载中UI
  }

  return (
    <View>
      // Return Code
    </View>
  );
};

export default App;

3. 多文件Auth代码的修改要求

所有使用getAuth()的文件,都需要改为导入ConfigFirebase中导出的统一auth实例,而非每次调用getAuth()。这样做的好处:

  • 确保全项目使用同一个Auth实例,避免初始化冲突
  • 统一持久化配置,所有业务场景都会生效
  • 减少重复代码,提升代码规范性

示例(其他业务文件):

// 替换原有的import { getAuth } from 'firebase/auth';
import { auth } from './path/to/ConfigFirebase';
// 直接使用auth实例调用API,如signInWithEmailAndPassword(auth, email, password)

关键注意事项

  • Expo Go环境下必须显式配置getReactNativePersistence(AsyncStorage),默认持久化机制无法正常工作
  • 确保@react-native-async-storage/async-storage已正确安装(Expo项目无需额外配置)
  • onAuthStateChanged返回的监听函数必须在组件卸载时取消,避免内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:39:59