Error: Uncaught (in promise): TypeError: Cannot set property 'isAdmin' of null

帅比萌擦擦* 提交于 2019-12-10 13:35:31

问题


firebase.auth().onAuthStateChanged((user) => {
  if(user) {
    this.isLoggedIn = true; //Set user loggedIn is true;
    this.isAdmin = false;
    firebase.database().ref('/userProfile/' + user.uid).once('value').then(function(snapshot) {
      let userInfo = snapshot.val();
      if(userInfo.isAdmin == true) {
        //ERROR AT THIS LINE: 
        //Error: Uncaught (in promise): TypeError: Cannot set property 'isAdmin' of null
        this.isAdmin = true;
        console.log(userInfo);
      }
    });
  } else {
    this.isLoggedIn = false; //Set user loggedIn is false;
  }
});

I'm getting error at line no.8

Error: Uncaught (in promise): TypeError: Cannot set property 'isAdmin' of null


回答1:


Either you can use arrow function

firebase.database().ref('/userProfile/' + user.uid).once('value')
.then((snapshot) => {

or use

var self = this;

firebase.database().ref('/userProfile/' + user.uid).once('value')
.then(function(snapshot) {
   self.isAdmin = true;

otherwise this doesn't point to the current function when it's called.

See also https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions



来源:https://stackoverflow.com/questions/38807643/error-uncaught-in-promise-typeerror-cannot-set-property-isadmin-of-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!