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); }); };
额外排查点(解决潜在深层问题)
绑定Auth实例到Firebase App
在firebase.js中,明确将初始化的app传入getAuth,避免隐式实例导致的异常:// 原代码 export const auth = getAuth(); // 修改为 export const auth = getAuth(app);清理依赖缓存
- 执行
expo r -c清除Expo缓存 - 删除
node_modules和package-lock.json/yarn.lock,重新执行npm install/yarn install
- 执行
监听Auth状态变化
通过onAuthStateChanged排查是否存在未预期的状态切换:onAuthStateChanged(auth, (user) => { console.log("Auth state changed: ", user); });
内容的提问来源于stack exchange,提问作者Butri
相关产品推荐
相关产品推荐

