JS:'this'上下文在承诺链中时一直显示为未定义



我在访问then()承诺链中的this上下文时遇到问题。 当我在调试器在then()内停止后尝试查看this的值时,我感到undefined
我搜索了之前关于这个问题的问题,并根据答案,我尝试在范围之外创建一个变量foo等于this但当我尝试在调试器停止代码时查看它的值时

,它也返回为未定义。
updateQuantity: function(e,item) {
if (e === null || e === "") {
return
}
let originalQuantity = item.original_quantity;
let updatedQuantity  = parseFloat(e)
var foo = this;
// can access other functions here, ex: this.updateName();
axios.post('/api/inventory/' + item.inventory_id + '/update-quantity', {
original_quantity: item.original_quantity,
quantity: updatedQuantity
})
.then(response => {
if (response.data && response.data.status == "success") {
this.showFlashMsg(response.data.message, true)
debugger
} else if (response.data && response.data.status == "error") {
debugger
}
})
.catch(err => {
console.log(err);
});
},

看起来你很接近。

TLDR; 至少在使用 Typescript 或更新的 EcmaScript (JS( 版本时,使用 lambda 函数 (=>( 会将this绑定到正确的对象,因此 Saurabh Agrawal 的评论。

当使用JS/EcmaScript的旧变体时,你必须获取对要传递到链式方法中的this的引用,然后使用它而不是this。如果我记得的话,这也是 Typescript 或其他转译器在定位旧版本时使用的。

使用您的代码(未经测试(,如下所示:

updateQuantity: function(e,item) {
if (e === null || e === "") {
return
}
let originalQuantity = item.original_quantity;
let updatedQuantity  = parseFloat(e)
// ADDED COMMENT -- looks like you already had a reference, just weren't using it
var foo = this;
// can access other functions here, ex: this.updateName();
axios.post('/api/inventory/' + item.inventory_id + '/update-quantity', {
original_quantity: item.original_quantity,
quantity: updatedQuantity
})
.then(response => {
if (response.data && response.data.status == "success") {
// EDIT -- use your variable reference to `this`
foo.showFlashMsg(response.data.message, true)
debugger
} else if (response.data && response.data.status == "error") {
debugger
}
})
.catch(err => {
console.log(err);
});
},

最新更新