expo-google-sign-in触发signInAsync并发运行错误的排障问询
报错根因拆解
expo-google-sign-in内置单运行任务锁机制,同一时间仅允许一个原生Google登录流程执行。当存在残留未完成的任务、或重复触发登录调用时,就会抛出当前的并发任务报错。- 初始化逻辑缺失:代码中将
GoogleSignIn.initAsync的初始化逻辑完全注释,未完成SDK初始化就直接调用登录接口,会导致内部状态异常、任务卡滞,触发并发检测。 - 点击无防重处理:登录按钮的点击回调未加状态拦截,用户快速多次点击时会连续多次调用
signInAsync,直接触发库的并发校验规则。 - 异常状态无清理:
signInAsync调用没有配套的异常捕获、状态重置逻辑,一旦出现网络中断、用户取消登录的情况,残留的任务标记不会被清除,后续所有登录调用都会被判定为并发任务。
修复实现方案
- 恢复SDK初始化流程,修正useEffect的异步用法:不要直接将async函数作为useEffect的入参,要在effect内部定义异步执行函数,保证初始化流程在组件挂载时正常执行,避免SDK状态异常。
- 增加登录状态锁:用
useRef保存登录流程的执行标记,在发起登录前先校验标记状态,拦截所有重复触发的登录请求。 - 补全完整的流程兜底:给登录逻辑加
try/catch/finally块,不管登录成功、失败、用户主动取消,都要在finally块中重置状态锁、清理残留的任务标记。 - 兜底清理卡滞状态:如果遇到之前残留的卡滞任务,可在初始化阶段主动调用
GoogleSignIn.signOutAsync清理上一次的未完成会话,解除内部的任务锁。
修复后的参考代码
import * as React from 'react'; import { useEffect, useRef } from 'react'; import { StyleSheet, Image, Pressable, ImageBackground, Alert } from 'react-native'; import * as GoogleSignIn from 'expo-google-sign-in'; export default function TabTwoScreen() { // 登录状态锁,防止重复触发 const isSigningInRef = useRef(false); // 组件挂载时完成SDK初始化 useEffect(() => { let isMounted = true; const initGoogleSignIn = async () => { try { // 先清理可能残留的卡滞会话 await GoogleSignIn.signOutAsync().catch(() => {}); await GoogleSignIn.initAsync({ clientId: '435403173197-1ofadf8gflla92ibd6ibveb4tvv1vice.apps.googleusercontent.com', }); } catch (e) { if (isMounted) { Alert.alert('Google登录初始化失败', e.message); } } }; initGoogleSignIn(); return () => { isMounted = false; }; }, []); const handleGoogleSignIn = async () => { // 拦截重复触发的登录请求 if (isSigningInRef.current) return; isSigningInRef.current = true; try { const user = await GoogleSignIn.signInAsync(); // 登录成功后的业务逻辑处理 console.log('登录成功', user); } catch (e) { Alert.alert('登录失败', e.message); } finally { // 不管流程结果如何,都重置锁状态 isSigningInRef.current = false; } }; return ( <View style={styles.container}> <ImageBackground source={require("../assets/images/happy-tiny-people-listening-spiritual-music/5870.jpg")} style={styles.background} > <Pressable onPress={handleGoogleSignIn} style={({ pressed }) => [{ backgroundColor: pressed ? 'white' : '#03befc' }, styles.google]} > <Image source={require("../assets/google_signin.png")} style={styles.googleImage}/> <Text style={styles.googleText}>Sign In With Google</Text> </Pressable> </ImageBackground> </View> ); } // 原有样式保持不变 const styles = StyleSheet.create({ container: { flex: 1 }, background: { flex: 1, justifyContent: 'center' }, google: { flexDirection: 'row', alignItems: 'center', padding: 12, borderRadius: 8, marginHorizontal: 32 }, googleImage: { width: 24, height: 24, marginRight: 12 }, googleText: { color: 'white', fontSize: 16 } });
额外注意:如果开发调试阶段遇到无法解除的卡滞状态,可直接重启开发服务、重新加载应用,让SDK的原生层状态锁完全重置,避免旧的任务标记一直驻留。
内容的提问来源于stack exchange,提问作者zendevil
相关产品推荐
相关产品推荐

