Firebase的onAuthStateChanged调用后始终返回undefined如何解决
问题原因
你代码的核心问题是 onAuthStateChanged 属于异步监听方法,回调函数内的 return 只会把值返回给回调本身,外层的 checkAuthState 没有定义任何返回逻辑,所以调用后默认返回 undefined。之前能正常运行属于巧合,大概率是你此前的逻辑直接在回调内处理结果,没有依赖该函数的返回值。
修复方案
方案1:封装为Promise(推荐,适用于单次获取登录状态/用户信息的场景)
这种方案符合你原本想要直接拿到返回值的调用习惯,仅需要配合 async/await 或者 .then 使用即可:
import { getAuth, onAuthStateChanged, User } from "firebase/auth"; export default function checkAuthState(type?: string): Promise<boolean | User> { const auth = getAuth(); return new Promise((resolve) => { // 注册监听后拿到取消方法,拿到结果后立即取消监听避免内存泄漏 const unsubscribe = onAuthStateChanged(auth, (user) => { unsubscribe(); if (user) { resolve(type === "getUser" ? user : true); } else { resolve(false); } }); }); }
调用示例:
// 方式1:async/await 调用 const isLogin = await checkAuthState(); // 返回布尔值 const user = await checkAuthState("getUser"); // 返回用户对象/布尔值 // 方式2:.then 调用 checkAuthState("getUser").then(user => { console.log(user); })
方案2:回调传参(适用于需要持续监听登录状态变化的场景)
如果你需要在登录状态变更时自动触发逻辑,就用回调方式实现:
import { getAuth, onAuthStateChanged, User } from "firebase/auth"; // callback 参数用于接收返回结果,函数返回值为取消监听的方法 export default function checkAuthState(type?: string, callback: (res: boolean | User) => void): () => void { const auth = getAuth(); return onAuthStateChanged(auth, (user) => { if (user) { callback(type === "getUser" ? user : true); } else { callback(false); } }); }
调用示例:
// 调用后拿到取消监听的方法,不需要监听时调用即可避免内存泄漏 const unsubscribe = checkAuthState("getUser", (user) => { // 登录状态变更时自动执行这里的逻辑 console.log("当前用户:", user); }); // 组件卸载/不需要监听时执行 // unsubscribe()
内容的提问来源于stack exchange,提问作者woop de schwoop
相关产品推荐
相关产品推荐

