React Native配置Firebase SMS验证遇Recaptcha原型未定义错误
React Native Firebase短信验证错误:TypeError: Cannot read property 'prototype' of undefined
核心原因
你使用了Web版Firebase Auth的RecaptchaVerifier,但React Native环境不存在window对象,且Web版reCAPTCHA组件完全不兼容RN运行环境,这是触发错误的根本原因。另外原代码还存在循环调用、类型错误和无效导入的问题。
解决方案步骤
1. 替换为React Native专用的Firebase依赖
卸载Web版firebase包,安装官方维护的RN Firebase套件:
npm uninstall firebase npm install @react-native-firebase/app @react-native-firebase/auth # iOS用户需执行pod安装 cd ios && pod install && cd ..
2. 简化Firebase配置文件(FirebaseConfig.js)
RN Firebase会自动读取安卓的google-services.json和iOS的GoogleService-Info.plist配置,无需手动编写firebaseConfig:
import auth from '@react-native-firebase/auth'; export { auth };
3. 重写短信验证逻辑(Signup.js)
RN中Firebase短信验证不需要手动处理reCAPTCHA,平台会自动完成设备级验证(安卓安全网、iOS设备校验),直接使用signInWithPhoneNumber即可:
import { useState } from 'react'; import { View, TextInput, Button, Alert } from 'react-native'; import { auth } from '../FirebaseConfig'; const Signup = () => { const [phoneNumber, setPhoneNumber] = useState(''); const [verificationCode, setVerificationCode] = useState(''); let confirmationResult = null; // 发送验证码 const sendVerificationCode = async () => { try { const formattedPhone = `+972${phoneNumber}`; confirmationResult = await auth.signInWithPhoneNumber(formattedPhone); Alert.alert('提示', '验证码已发送至您的手机'); } catch (error) { console.error('发送失败:', error.message); Alert.alert('错误', error.message); } }; // 验证验证码 const verifyVerificationCode = async () => { try { await confirmationResult.confirm(verificationCode); Alert.alert('成功', '手机号验证通过'); // 后续可处理登录/注册逻辑 } catch (error) { console.error('验证失败:', error.message); Alert.alert('错误', '验证码无效或已过期'); } }; return ( <View style={{ padding: 20, gap: 15 }}> <TextInput placeholder="输入手机号(不含+972)" value={phoneNumber} onChangeText={setPhoneNumber} keyboardType="phone-pad" style={{ borderBottomWidth: 1, paddingVertical: 8 }} /> <Button title="发送验证码" onPress={sendVerificationCode} /> {confirmationResult && ( <> <TextInput placeholder="输入6位验证码" value={verificationCode} onChangeText={setVerificationCode} keyboardType="number-pad" maxLength={6} style={{ borderBottomWidth: 1, paddingVertical: 8 }} /> <Button title="验证验证码" onPress={verifyVerificationCode} /> </> )} </View> ); }; export default Signup;
4. 平台额外配置
- 安卓:在Firebase控制台启用「安全网」,确保
google-services.json已正确放置在android/app目录。 - iOS:在Xcode中开启「推送通知」权限,添加「后台模式」的「远程通知」,并将APNs证书上传至Firebase控制台。
原代码的其他问题修正
- 移除了无效的
import { firebase } from "firebase/app";,模块化SDK无需全局导入。 - 将手机号的
useState(0)改为useState(''),避免数字类型导致的格式错误。 - 修复了
onSignup与onCaptchVerify的循环调用问题。 - 移除了所有依赖
window的代码,RN无此全局对象。
内容的提问来源于stack exchange,提问作者Zachary Amdur
相关产品推荐
相关产品推荐

