Expo+React Native中Firebase谷歌登录报错:Cannot read property '_getIdTokenResponse' of undefined
解决Expo + React Native中Google登录Firebase报错:Cannot read property '_getIdTokenResponse' of undefined
问题概述
在Expo + React Native环境下,使用@react-native-google-signin/google-signin库通过GoogleProvider登录Firebase时,出现错误:Cannot read property '_getIdTokenResponse' of undefined。
相关代码
import React, { useEffect, useState } from "react"; import { StyleSheet, View } from "react-native"; // Libs import { GoogleAuthProvider, signInWithCredential } from "firebase/auth"; import { GoogleSignin, GoogleSigninButton, } from "@react-native-google-signin/google-signin"; // App export default function GoogleAuth() { const [isInProgress, setInProgress] = useState(false); useEffect(() => { GoogleSignin.configure({ webClientId: 'xyz', offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER forceCodeForRefreshToken: true, // [Android] related to `serverAuthCode`, read the docs link below *. profileImageSize: 480, // [iOS] The desired height (and width) of the profile image. Defaults to 120px }); }, []); async function signIn() { try { setInProgress(true); await GoogleSignin.hasPlayServices(); const { idToken } = await GoogleSignin.signIn(); setInProgress(false); return signInWithCredential(GoogleAuthProvider.credential(idToken)); } catch (error) { // setInProgress(false); } } return ( <View style={styles.container}> <View style={styles.button}> <GoogleSigninButton size={GoogleSigninButton.Size.Icon} color={GoogleSigninButton.Color.Light} onPress={signIn} disabled={isInProgress} /> </View> </View> ); }
依赖版本
"expo": "^49", "react-native": "0.72.6", "firebase": "^10.7.2",
解决方案
1. 修复Firebase Auth调用参数(核心原因)
Firebase v9+模块化API中,signInWithCredential需要传入Auth实例作为第一个参数,你的代码中缺少该实例,导致报错。
步骤:
- 先初始化Firebase应用并获取Auth实例:
import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; // 替换为你的Firebase项目配置 const firebaseConfig = { apiKey: "你的API_KEY", authDomain: "你的AUTH_DOMAIN", projectId: "你的PROJECT_ID", storageBucket: "你的STORAGE_BUCKET", messagingSenderId: "你的MESSAGING_SENDER_ID", appId: "你的APP_ID" }; const app = initializeApp(firebaseConfig); const auth = getAuth(app);
- 修改
signIn函数中的调用:
return signInWithCredential(auth, GoogleAuthProvider.credential(idToken));
2. 验证GoogleSignin配置的webClientId
确保webClientId是Firebase控制台中Web应用的Client ID,而非Android/iOS的客户端ID。可在Firebase控制台「Authentication」→「登录方法」→「Google」中查看并复制。
3. 检查Expo环境适配
- 若使用Expo Managed Workflow,确认
@react-native-google-signin/google-signin版本与Expo 49兼容,或改用Expo官方的expo-google-sign-in库简化配置。 - 若使用Bare Workflow,确保已完成原生配置:Android端放置
google-services.json,iOS端放置GoogleService-Info.plist,并按库文档完成权限配置。
4. 确保依赖版本兼容
安装与当前Expo、React Native版本适配的@react-native-google-signin/google-signin版本:
npm install @react-native-google-signin/google-signin@latest
内容的提问来源于stack exchange,提问作者Abdul Sadik Yalcin
相关产品推荐
相关产品推荐

