Firebase电话认证报错:confirmationResult.confirm不是函数,请排查代码问题
问题原因及修复方案
核心问题
你在sendOtp函数中调用signInWithPhoneNumber时没有使用await,这个方法返回的是Promise对象,直接把Promise存入confirmationResult状态后,调用confirmationResult.confirm()自然会报错——因为Promise对象根本没有confirm方法。
修复步骤
- 在
signInWithPhoneNumber前添加await,等待Promise解析拿到真正的ConfirmationResult实例 - (可选)给RecaptchaVerifier添加基础配置,提升兼容性
修改后的完整代码
import { auth } from '../firebase-config' import React, { useState } from 'react'; import { RecaptchaVerifier, signInWithPhoneNumber } from 'firebase/auth' import PhoneInput from 'react-phone-input-2'; const Profile = ({ isLoggedIn }) => { const [phoneNumber, setPhoneNumber] = useState(''); const [otp, setOtp] = useState(''); const [confirmationResult, setConfirmationResult] = useState(null); const sendOtp = async () => { try { // 给Recaptcha添加明确配置,提升兼容性 const recaptcha = new RecaptchaVerifier(auth, "recaptcha", { size: "invisible", callback: (response) => { // 验证码验证成功后的回调,可留空或添加逻辑 } }); // 关键:添加await获取实际的ConfirmationResult const confirmation = await signInWithPhoneNumber(auth, phoneNumber, recaptcha); setConfirmationResult(confirmation); } catch (error) { console.log(error); // 可选:重置recaptcha避免重复报错 recaptcha.reset(); } } const verifyOtp = async () => { try { if (!confirmationResult) return; // 避免未发送OTP就点击验证的情况 const result = await confirmationResult.confirm(otp); // 验证成功后的逻辑,比如获取用户信息 console.log("登录成功", result.user); } catch (error) { console.log("验证错误: ", error); } } return ( <div> <div> <PhoneInput country={"in"} value={phoneNumber} onChange={(phone) => setPhoneNumber("+" + phone)} /> </div> <div id="recaptcha"></div> <button onClick={sendOtp}>send otp</button> <div> <input type="text" value={otp} onChange={(e) => setOtp(e.target.value)} /> </div> <button onClick={verifyOtp}>verify otp</button> </div> ); }; export default Profile;
额外提示
- 确保你的Firebase配置已经正确初始化,并且在控制台开启了电话认证方式
- 测试时使用真实的手机号(Firebase测试号码除外),避免被拦截
- 可以添加加载状态,防止用户重复点击发送/验证按钮
内容的提问来源于stack exchange,提问作者Vinith Vedmutha
相关产品推荐
相关产品推荐

