使用Firebase发送OTP时遇Uncaught TypeError错误的排查求助
错误原因及修复方案
你遇到的Uncaught TypeError: Cannot read properties of undefined (reading 'appVerificationDisabledForTesting')错误,核心原因是Firebase Auth实例未正确初始化,导致RecaptchaVerifier或signInWithPhoneNumber调用时无法获取到有效的Auth对象。以下是具体修复步骤:
1. 统一Firebase初始化,避免重复或错误初始化
不要在组件的componentDidMount中直接初始化Firebase,建议单独创建Firebase配置文件,确保初始化只执行一次并导出Auth实例:
创建src/firebase.js文件:
import { initializeApp } from 'firebase/app'; import { getAuth } from 'firebase/auth'; // 替换为你的Firebase项目配置 const firebaseConfig = { apiKey: "你的API_KEY", authDomain: "你的AUTH_DOMAIN", projectId: "你的PROJECT_ID", storageBucket: "你的STORAGE_BUCKET", messagingSenderId: "你的MESSAGING_SENDER_ID", appId: "你的APP_ID" }; // 初始化Firebase应用 const app = initializeApp(firebaseConfig); // 导出预初始化的Auth实例 export const auth = getAuth(app);
然后在组件中导入这个预初始化的Auth实例,代替每次调用getAuth():
import { RecaptchaVerifier, signInWithPhoneNumber} from 'firebase/auth'; import { auth } from './firebase'; // 导入Auth实例
2. 修复RecaptchaVerifier的创建逻辑
无需将appVerifier挂载到window全局变量,直接在组件内管理即可,同时确保DOM元素已存在:
sendCode() { // 先检查recaptcha容器是否存在 const recaptchaContainer = document.getElementById('recaptcha-container'); if (!recaptchaContainer) return; const appVerifier = new RecaptchaVerifier( recaptchaContainer, { size: "invisible" }, auth // 使用预初始化的Auth实例 ); this.setState({ mobile: this.props.mobile, disabled: false, }); const number = "+65" + this.props.mobile.trim(); // 去掉空格,避免号码格式错误 console.log(number); signInWithPhoneNumber(auth, number, appVerifier) .then((confirmationResult) => { // 使用箭头函数,保证this指向组件实例 console.log("Success"); window.confirmationResult = confirmationResult; this.setState({ confirmResult: confirmationResult }); console.log(confirmationResult); }) .catch(error => { // 务必添加错误捕获,排查问题 console.error("发送验证码失败:", error); }); }
3. 修复回调函数中的this指向问题
在signInWithPhoneNumber的then回调中使用箭头函数,避免普通function导致this指向丢失,进而引发后续this.setState报错。
4. 其他检查点
- 确认你的Firebase项目已启用电话号码登录方式(在Firebase控制台的Authentication -> 登录方法中开启)。
- 检查
firebaseConfig的所有字段是否与Firebase控制台中的配置完全一致,任何字段错误都会导致初始化失败。 - 确保页面中没有重复初始化Firebase应用的代码,重复调用
initializeApp会导致Auth实例异常。
内容的提问来源于stack exchange,提问作者Natasha
相关产品推荐
相关产品推荐

