Firebase移动端认证报错:TypeError: Cannot read property 'prototype' of undefined
React Native Firebase手机号OTP登录报错:TypeError: Cannot read property 'prototype' of undefined
问题代码
import firebase from 'firebase/app'; import auth from './firebaseConfig' import RecaptchaVerifier from 'firebase/auth' // Sent OTP const signin = () => { if (mynumber === "" || mynumber.length < 10) return; window.RecaptchaVerifier = new RecaptchaVerifier(auth,'recaptcha-container',{}); const appVerifier = window.RecaptchaVerifier signInWithPhoneNumber(auth, mynumber, appVerifier).then((result) => { }); }
报错信息
TypeError: Cannot read property 'prototype' of undefined, js engine: hermes at node_modules\react-native\Libraries\Core\ExceptionsManager.js:null in reportException at node_modules\react-native\Libraries\Core\ExceptionsManager.js:null in handleException ... 7 more stack frames from framework internals
错误原因
- 导入错误:
RecaptchaVerifier和signInWithPhoneNumber未正确导入,且React Native环境不支持web版的RecaptchaVerifier(依赖DOM元素) - window对象误用:React Native中不存在浏览器的
window全局对象 - 组件不兼容:
'recaptcha-container'是web端的DOM容器ID,React Native中无法识别该元素
解决方案
推荐使用官方适配React Native的@react-native-firebase库,而非web版firebase包,步骤如下:
1. 安装依赖
npm install @react-native-firebase/app @react-native-firebase/auth
2. 修正后的代码示例
import auth from '@react-native-firebase/auth'; import { useState } from 'react'; // 保存OTP确认对象 const [confirmation, setConfirmation] = useState(null); // 发送OTP const signin = async () => { if (!mynumber || mynumber.length < 10) return; try { // 可选:配置应用内处理OTP的设置 const actionCodeSettings = { handleCodeInApp: true, url: 'https://yourapp.page.link/otp', // 替换为你的APP关联链接 }; const confirmResult = await auth().signInWithPhoneNumber(mynumber, actionCodeSettings); setConfirmation(confirmResult); console.log('OTP已发送'); } catch (error) { console.error('发送OTP失败:', error.message); } }; // 验证OTP const verifyOTP = async (otpCode) => { if (!confirmation || !otpCode) return; try { await confirmation.confirm(otpCode); console.log('登录成功'); // 登录成功后可跳转首页或处理用户信息 } catch (error) { console.error('OTP验证失败:', error.message); } };
关键说明
- 使用
@react-native-firebase/auth适配React Native环境,无需依赖web端的Recaptcha组件,Firebase会自动处理设备级验证 - 移除
window对象的使用,改用React状态管理保存OTP确认对象 - 用
async/await替代链式then,代码更易读和维护
内容的提问来源于stack exchange,提问作者Lakshay
相关产品推荐
相关产品推荐

