When es6 deconstructs the method of assignment, it will result in the loss of this.

Today, when I was using es6 to deconstruct the assignment introduction method, I found that I could not get the details of this, in the method.

paste code first:

    /*mainVM*/
    @observable planDetailList = [];
    @action
    ajaxPlanDetailList(id,callback){
        Helper.ajax(Api.planList+"/"+id,{
            method:"GET"
        }).then(res => {
            console.log(this);
        })
    }
    /*componentDidMountmainVM*/
    componentDidMount() {
        const { ajaxPlanDetailList } = this.props.mainVM;
        ajaxPlanDetailList(this.props.id);
    }

displays the following error

clipboard.png

mainVM


clipboard.png

got the this

I don"t quite understand the reason. Please explain it in detail and kneel down and thank you

.
Mar.03,2021

two ideas
1 write ajaxPlanDetailList as an arrow function
2 ajaxPlanDetailList bind this similar to ajaxPlanDetailList.bind (this)


functions cannot use structures, right?

 const { ajaxPlanDetailList } = this.props.mainVM;
 //ajaxPlanDetailList(this.props.id);
         ajaxPlanDetailList

follow-up issues have been followed


if you don't deconstruct the assignment, you will lose the this context, for example, obj.ajaxPlanDetailList () , then this is obj , and if you directly ajaxPlanDetailList () , this is the global object window .

function fun() {
  console.log(this.a);
}

let obj1 = {
  a: 1,
  fun: fun
};

let obj2 = {
  a: 2,
  fun: fun
};

let a = 3;

obj1.fun();  // 1
obj2.fun();  // 2
fun();  // 3
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e9637d-15b9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e9637d-15b9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?