首页 > 解决方案 > 在js的回调中使用公共函数时无法读取属性错误

问题描述

我有一个类,假设 A,它有两个函数 AA 和 BB,如下所示。

export class A {
    constructor(){}

    public async AA(X){
     return true;
    }

    public async BB(){
       var users=new Users({      // db model
         name: 'test'
       });

       users.save(function(err,data){
         if(err){
           console.log(err);
         }else{
            var result = await this.AA(data);   // Cannot read property 'AA' of null
         }
       });
    }

}

我不确定如何在回调函数中访问或使公共函数 AA 可用。

我收到错误: TypeError: Cannot read property 'addRecipient' of null

标签: javascriptfunctionscope

解决方案


1)您似乎将 User 类实例分配给了 users 变量。

但是在这里,你正在使用user而不是users

2)问题在于此操作 user.save(function(err,data){ if(err){ console.log(err); }else{ var result = await this.AA(data); // Cannot read property 'AA' of null } });

函数中的 this 关键字与类中的全局 this 具有不同的范围

如果可以,将函数转换为箭头函数

user.save((err,data) => {
     if(err){
       console.log(err);
     }else{
        var result = await this.AA(data);   // 
Cannot read property 'AA' of null
     }
   });

或者你可以通过全局范围有一个变量,然后利用它。

var self = this;
user.save(function(err,data){
     if(err){
       console.log(err);
     }else{
        var result = await self.AA(data);   // 
Cannot read property 'AA' of null
     }
   });

推荐阅读