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

退出应用时控制台报错Cannot read property 'uid' of null的问题排查

Fixing "Cannot read property 'uid' of null" on App Exit

Let's break down exactly what's causing this error and fix it for you. The issue pops up when users log out because Firebase's onAuthStateChanged callback fires with user = null (since there's no authenticated user anymore). Your current code doesn't handle this null state, so when you try to access this.currentUser.uid, you're trying to read a property from a null value—hence the error.

Here's how to resolve this step by step:

  • Handle the logout (null user) case first
    Add an explicit check at the start of the callback to reset your variables when there's no authenticated user. This stops any attempts to access properties on a null value.

  • Use the callback's user parameter directly
    The user passed to onAuthStateChanged is already the current authenticated user (or null), so calling firebase.auth().currentUser again is redundant and less reliable. Just use the parameter directly.

Modified Working Code

constructor(private firestore: AngularFirestore, private auth: AuthService) {
  firebase.auth().onAuthStateChanged(user => {
    // Handle logout scenario first
    if (!user) {
      this.currentUser = null;
      this.vendor = null; // Reset the vendor reference too to avoid stale data
      return;
    }

    // Only update if the user state actually changed
    if (this.currentUser !== user) {
      this.currentUser = user;
      this.vendor = firebase.firestore().doc(`/Products/${this.currentUser.uid}`);
    }
  });
}

Extra Tips for Better Angular + Firebase Integration

  • Switch to AngularFireAuth
    Since you're already using AngularFirestore, it’s cleaner to use the AngularFire ecosystem for authentication too. It provides observables that integrate seamlessly with Angular's lifecycle:
    import { AngularFireAuth } from '@angular/fire/compat/auth';
    
    constructor(private firestore: AngularFirestore, private afAuth: AngularFireAuth) {
      this.afAuth.authState.subscribe(user => {
        if (!user) {
          this.currentUser = null;
          this.vendor = null;
          return;
        }
    
        if (this.currentUser !== user) {
          this.currentUser = user;
          this.vendor = this.firestore.doc(`/Products/${user.uid}`); // Use AngularFirestore's doc method too
        }
      });
    }
    
  • Clean up subscriptions
    If you use observables (like with AngularFireAuth), remember to unsubscribe when your component is destroyed to prevent memory leaks. You can store the subscription in a variable and call unsubscribe() in the ngOnDestroy hook.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:38:20