首页 > 解决方案 > Firebase 何时触发 onAuthStateChanged?

问题描述

如果我的 createUserWithEmailAndPassword 函数结构如下

    await auth.createUserWithEmailAndPassword(email, password).then((userCredential) => {
        code stuff...
        return promise
    }).then(() => {
        ...
    }).catch(() => {
        ...
    }).finally(() => {
        ...
    })

在承诺链中,onAuthStateChanged 观察者何时会启动?

标签: firebasefirebase-authentication

解决方案


仅当onAuthStateChanged用户登录或注销时才会触发观察者。

文档中:

在 4.0.0 之前,当用户登录、退出或用户的 ID 令牌在令牌到期或密码更改等情况下发生更改时,这会触发观察者。4.0.0 之后,观察者只在登录或注销时触发。

要保留旧行为,请参阅firebase.auth.Auth.onIdTokenChanged

话虽如此,如果您有onAuthStateChanged观察者,它将在用户登录后立即触发,并且您.then()块内的代码可能会或可能不会完全执行。如果您的身份验证观察者在登录后将用户重定向到其他页面,那么您的用户很可能会在您的 then 块完成之前被重定向。

如果您需要在用户登录后执行一些代码,您应该取消订阅 auth 观察者:

const auth = firebase.auth()

const authObserver = auth.onAuthStateChanged((user) => {
  if (user) {
    // redirect
  }
})


btnLogin.onclick = async function () {
  //unsubscribe
  authObserver()

  await auth.createUserWithEmailAndPassword(email, password).then((userCredential) => {
        // onAuthStateChanged will trigger here if not disabled
        //code stuff...
        //return promise
    }).then(() => {
        // your code
    })
}

推荐阅读