You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase邮箱/密码登录失败:Cannot read property 'then' of undefined

问题分析与解决方案

核心语法错误(直接触发报错)

你的代码存在明显的逻辑语法问题:在async函数中,你先用await调用signInWithEmailAndPassword,随后执行console.log语句,紧接着链式调用.then——这相当于在console.log的返回值(undefined)上调用.then,必然会抛出"Cannot read property 'then' of undefined"错误。

修复后的代码示例

二选一即可,不要混用await和.then/.catch:

写法1:用await + try/catch(适配async函数风格)

const addRating = async (id, rating) => { 
    try {
        console.log('auth: ', auth)
        console.log('email: ', email)
        console.log('password: ', password)
        
        const userCredential = await signInWithEmailAndPassword(auth, email, password)
        console.log('userCredential: ', userCredential)
        const user = userCredential.user;             
        // 执行后续Realtime Database读写逻辑
    } catch (error) {
        const errorCode = error.code;
        const errorMessage = error.message;
        console.log("addReviewRequest failing to log to firebase with: " + errorCode + " - " + errorMessage);
    }
};

写法2:用.then/.catch(不使用await)

const addRating = (id, rating) => { 
    console.log('auth: ', auth)
    console.log('email: ', email)
    console.log('password: ', password)
    
    signInWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {     
        console.log('userCredential: ', userCredential)
        const user = userCredential.user;             
        // 执行后续Realtime Database读写逻辑
    })
    .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        console.log("addReviewRequest failing to log to firebase with: " + errorCode + " - " + errorMessage);
    });
};

额外排查点(解决潜在深层问题)

  1. 绑定Auth实例到Firebase App
    在firebase.js中,明确将初始化的app传入getAuth,避免隐式实例导致的异常:

    // 原代码
    export const auth = getAuth();
    // 修改为
    export const auth = getAuth(app);
    
  2. 清理依赖缓存

    • 执行expo r -c清除Expo缓存
    • 删除node_modules和package-lock.json/yarn.lock,重新执行npm install/yarn install
  3. 监听Auth状态变化
    通过onAuthStateChanged排查是否存在未预期的状态切换:

    onAuthStateChanged(auth, (user) => {
      console.log("Auth state changed: ", user);
    });
    

内容的提问来源于stack exchange,提问作者Butri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 19:37:32