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

Expo中调用auth().signInWithCredential时Firebase初始化错误修复

问题分析与解决方案

问题原因

  1. Firebase初始化未全局触发:你虽然创建了firebase.js配置文件,但如果没有在应用入口(如App.js或index.js)导入该文件,初始化代码就不会执行,导致Firebase默认应用未创建。
  2. Auth模块导入与使用错误:你直接从@react-native-firebase/auth导入auth,而非从已初始化的firebase.js导出的实例,调用auth()时无法关联到已初始化的应用;同时GoogleAuthProvider的调用方式也不符合@react-native-firebase的规范。

解决步骤

步骤1:确认firebase.js的正确配置

确保你的firebase.js包含完整的初始化逻辑并导出实例:

// ../firebase.js
import firebase from '@react-native-firebase/app';
import '@react-native-firebase/auth';
import '@react-native-firebase/firestore';

// 替换为你的Firebase配置信息
const firebaseConfig = {
  apiKey: "你的API_KEY",
  authDomain: "你的AUTH_DOMAIN",
  projectId: "你的PROJECT_ID",
  storageBucket: "你的STORAGE_BUCKET",
  messagingSenderId: "你的MESSAGING_SENDER_ID",
  appId: "你的APP_ID"
};

// 避免重复初始化
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

// 导出已初始化的auth和firestore实例
export const auth = firebase.auth();
export const db = firebase.firestore();

步骤2:在应用入口触发初始化

打开App.js或index.js,在顶部添加导入,确保初始化逻辑在应用启动时执行:

import '../firebase'; // 根据你的文件路径调整

步骤3:修正组件中的导入与Auth调用

替换组件中的导入方式,并调整onGoogleButtonPress函数:

// 替换原有导入,从firebase.js导出实例
import { auth, db } from "../firebase";
import { arrayUnion } from "firebase/firestore";
import { useEffect, useState } from "react";
import { GoogleSignin } from "@react-native-google-signin/google-signin";

useEffect(() => {
  GoogleSignin.configure({
    webClientId: "13653657738-te8npgeck2gcee4u33rrdjpf5u1sr1c9.apps.googleusercontent.com",
  });
}, []);

async function onGoogleButtonPress() {
  const { idToken } = await GoogleSignin.signIn();
  // 使用firebase内置的GoogleAuthProvider
  const googleCredential = firebase.auth.GoogleAuthProvider.credential(idToken);
  // 直接调用已初始化的auth实例的signInWithCredential方法
  return auth.signInWithCredential(googleCredential);
}

步骤4:修复TouchableOpacity中的语法错误

清理注释残留的错误代码,修正用户数据更新逻辑:

<TouchableOpacity
  onPress={() => {
    onGoogleButtonPress()
      .then((userCredential) => {
        const user = userCredential.user;
        console.log("登录成功", user);
        // 更新当前登录用户的Firestore数据,替换固定的"userId"为用户真实uid
        return db.collection("users")
          .doc(user.uid)
          .update({ ids: arrayUnion(user.uid) });
      })
      .then(() => {
        navigation.navigate("Procedure");
      })
      .catch((e) => {
        console.log("登录失败", e.message);
      });
  }}
>
  <Image
    source={require("../assets/googlebutton.png")}
    style={{ maxWidth: 350, maxHeight: 63 }}
    alt="Google Button"
  />
</TouchableOpacity>

额外检查

  • 确保@react-native-firebase/auth、@react-native-google-signin/google-signin的版本与你的React Native版本兼容。
  • 确认Android的google-services.json和iOS的GoogleService-Info.plist已正确放置在对应目录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:07:48