简体   繁体   中英

TypeError: Cannot read property 'userId' of undefined in promise?

Why I can not get property userId inside class?

   connection
          .start()
          .then(function() {
            connection
              .invoke("join", this.userId)
              .then(function() {
                this.pushPassportData();
              })
              .catch(err => console.error(err.toString()));
          })
          .catch(function(err) {
            return console.error(err.toString());
          });

In this line:

 .invoke("join", this.userId)

userId is declared as private property class.

this inside your anonymous function refers to window , you can use arrow functions instead to solve this problem:

Try the following:

connection
          .start()
          .then(()=> {
            connection
              .invoke("join", this.userId)
              .then(()=> {
                this.pushPassportData();
              })
              .catch(err => console.error(err.toString()));
          })
          .catch(err=> {
            return console.error(err.toString());
          });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM