React Native Expo安卓谷歌登录模块RNGoogleSignin空对象报错求解
问题原因
该报错本质是@react-native-google-signin/google-signin的安卓原生模块没有成功注入到JS运行环境,导致RNGoogleSignin对象为null,读取属性时触发空指针异常。针对你使用的Expo环境+对应依赖版本,按以下步骤排查解决:
解决方案
- 第一步:修正依赖版本兼容性
你当前使用的@react-native-google-signin/google-signin@7.0.0-alpha.3是测试版,本身稳定性不足,且和react-native@0.63.2存在适配缺陷。先卸载当前版本,安装适配你RN版本的稳定版:
# npm执行 npm uninstall @react-native-google-signin/google-signin npm install @react-native-google-signin/google-signin@6.0.0 # yarn执行 yarn remove @react-native-google-signin/google-signin yarn add @react-native-google-signin/google-signin@6.0.0
- 第二步:补充Expo专属配置
Expo框架不能直接使用原生模块默认的链接逻辑,需要安装Expo适配包后重新构建自定义开发客户端,Expo Go默认没有集成谷歌登录的原生能力,无法直接运行该模块:
expo install @react-native-google-signin/google-signin # 构建安卓端自定义开发客户端 eas build --profile development --platform android
- 第三步:添加安卓谷歌服务配置
在app.json的expo.android节点下新增谷歌服务文件配置,同时把你从谷歌云后台下载的google-services.json文件放到项目根目录:
{ "expo": { "android": { "googleServicesFile": "./google-services.json" } } }
- 第四步:修正业务代码逻辑
你当前直接在组件顶层执行登录逻辑,属于无触发的提前调用,且没有异常捕获,建议调整为事件触发+异常捕获的写法:
import React, { useEffect } from "react"; import { View, Text, StyleSheet, TouchableOpacity } from "react-native"; import { GoogleSignin, statusCodes } from '@react-native-google-signin/google-signin'; const Splash = () => { // 初始化逻辑放到useEffect仅执行一次 useEffect(() => { GoogleSignin.configure({ webClientId: '265662725956-ukku7c59o0afjqpig79bdcsrdnai4063.apps.googleusercontent.com' }); }, []) const handleGoogleLogin = async () => { try { await GoogleSignin.hasPlayServices(); const userInfo = await GoogleSignin.signIn(); console.log('登录成功', userInfo); } catch (error) { if (error.code === statusCodes.SIGN_IN_CANCELLED) { console.log('用户取消登录') } else if (error.code === statusCodes.IN_PROGRESS) { console.log('登录操作正在进行') } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) { console.log('谷歌服务不可用') } else { console.log('其他登录错误', error) } } } return ( <View style={styles.BGContainer}> <TouchableOpacity onPress={handleGoogleLogin}> <Text>点击谷歌登录</Text> </TouchableOpacity> </View> ); } const styles = StyleSheet.create({ BGContainer: { flex: 1, alignItems: 'center', justifyContent: 'center' } }) export default Splash;
- 第五步:清理缓存重启项目
配置完成后执行命令清理缓存再启动:
npx react-native start --reset-cache
用你构建的自定义Expo开发客户端打开项目即可正常触发谷歌登录流程。
内容的提问来源于stack exchange,提问作者Rajkumar Gour
相关产品推荐
相关产品推荐

