更新时间:2023-12-01 15:56:58
在分配user
变量之前,您需要等待onAuthStateChanged
触发,否则Auth对象可能处于中间状态.这是记录:
You need to wait for onAuthStateChanged
to fire before assigning the user
variable, otherwise the Auth object may be in an intermediate state. This is documented:
通过使用观察者,您可以确保在获得当前用户时,Auth对象不处于中间状态(例如初始化).当您使用signInWithRedirect时,onAuthStateChanged观察者将等到getRedirectResult解析后再触发.
By using an observer, you ensure that the Auth object isn't in an intermediate state—such as initialization—when you get the current user. When you use signInWithRedirect, the onAuthStateChanged observer waits until getRedirectResult resolves before triggering.
您还可以使用currentUser属性获取当前登录的用户.如果未登录用户,则 currentUser为空:
You can also get the currently signed-in user by using the currentUser property. If a user isn't signed in, currentUser is null:
值得明确指出的是,您在onAuthStateChanged
中的user
变量与在updateProfile
方法中使用的user
变量不同.虽然用户可能在onAuthStateChanged
触发时登录",但是在设置外部user
变量时,他们很可能未登录.这就是您的问题所在.
It's worth explicitly pointing out that the user
variable you console.log
in onAuthStateChanged
is not the same user
variable that's used in your updateProfile
method. While the user maybe "logged in" when onAuthStateChanged
fires, they are likely not logged in when you set your outer user
variable. Therein lies your problem.
从您的代码中尚不清楚在何处调用updateProfile
,但是彼得·哈达德的答案可能是我会解决的方法实行.但是,请注意,使用该答案中提供的代码段,您还需要更改updateProfile
方法以接受user
参数.另一种方法是在onAuthStateChanged
内部分配user
变量.
It's not clear from your code where updateProfile
is called, but Peter Haddad's answer is likely the solution I would implement. However, note that with the code snippet supplied in that answer you'll also need to change your updateProfile
method to accept a user
parameter. Another approach would be to assign the user
variable inside of onAuthStateChanged
.
let user;
auth.onAuthStateChanged(u => user = u);
使用这种方法,您的updateProfile
方法应该可以正常工作.请记住,您的通话条件可能会有所不同,具体取决于您何时致电updateProfile
.
With that approach your updateProfile
method should work as is. Just keep in mind that you may have a race condition depending on when you call updateProfile
.