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

React Native+Expo集成Firebase谷歌登录报错:signInWithPopup不是函数

解决React Native中Firebase谷歌登录的TypeError问题

错误原因分析

  1. signInWithPopup仅支持Web环境:你调用的signInWithPopup是Firebase Auth针对Web浏览器设计的API,React Native没有内置的弹出式浏览器环境,因此调用该方法会触发undefined is not a function错误。
  2. GoogleAuthProvider实例化错误:new GoogleAuthProvider(app)写法错误,GoogleAuthProvider的构造函数不需要传入app实例,正确写法是new GoogleAuthProvider()。

解决方案

第一步:修正Firebase配置文件

先修正你的firebase.js中GoogleAuthProvider的实例代码:

// firebase.js 修正后
import { initializeApp } from "firebase/app";
import { getAuth, GoogleAuthProvider } from 'firebase/auth';

const firebaseConfig = {
  // 你的Firebase配置
};

export const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
// 移除多余的app参数
export const provider = new GoogleAuthProvider();

第二步:替换React Native兼容的谷歌登录方法

由于Web SDK的signInWithPopup不支持React Native,推荐使用React Native Firebase库(专为React Native优化)来实现谷歌登录,步骤如下:

1. 安装依赖

# 安装React Native Firebase核心库和Auth模块
npm install @react-native-firebase/app @react-native-firebase/auth
# 安装谷歌登录原生模块
npm install @react-native-google-signin/google-signin

2. 配置原生项目

  • Android:将Firebase控制台下载的google-services.json放入android/app目录,配置build.gradle文件(参考官方文档的原生配置步骤)。
  • iOS:将GoogleService-Info.plist拖入Xcode项目,配置URL Scheme(从plist文件中获取REVERSED_CLIENT_ID作为URL Scheme)。

3. 实现谷歌登录逻辑

修改login.js中的handleGoogleSignIn方法:

// login.js 导入新增依赖
import { GoogleSignin } from '@react-native-google-signin/google-signin';
import auth from '@react-native-firebase/auth';

// 在组件外初始化GoogleSignin
GoogleSignin.configure({
  webClientId: '你的Web Client ID(从Firebase控制台 -> 认证 -> 登录方法 -> Google -> Web客户端ID获取)',
});

// 替换原有的handleGoogleSignIn
const handleGoogleSignIn = async () => {
  try {
    // 触发谷歌原生登录弹窗
    const { idToken } = await GoogleSignin.signIn();
    
    // 创建Firebase认证凭证
    const googleCredential = auth.GoogleAuthProvider.credential(idToken);
    
    // 完成Firebase登录
    const userCredential = await auth().signInWithCredential(googleCredential);
    
    console.log('谷歌登录成功', userCredential.user);
    navigation.navigate("Home", {username: userCredential.user.email});
  } catch (error) {
    console.error('登录失败', error);
  }
};

备选方案:使用Firebase Web SDK的signInWithRedirect(不推荐)

如果你坚持使用Firebase Web SDK,可替换signInWithPopup为signInWithRedirect,但需要配置React Native的深层链接来处理登录后的重定向,步骤繁琐且体验不如原生模块,因此更推荐上述React Native Firebase方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 07:37:46