javascript - JS:在承诺链中时,“this”上下文一直显示为未定义
问题描述
我在访问承诺链this
中的上下文时遇到问题。then()
当我undefined
尝试查看this
调试器在then()
.
我搜索了有关此问题的先前问题并根据答案,我尝试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);
});
},
推荐阅读
- java - 如何根据方法参数更改代码?
- python - Python:如何过滤多个列表字典?
- c - 如何检查密码直到正确?
- python - 为什么 NumPy 的方差结果与我的不同?
- javascript - 通过循环组合 2 个对象
- excel - 当我尝试将范围复制到工作表时,运行时错误 438 Oject 不支持属性或 mothos
- python - 使用 pandas 生成随机模拟的问题
- azure - 使用 Microsoft Graph Webhook
- c++ - 如何修复此代码我尝试了很多方法*悲伤*
- ubuntu - 如何修复“无法连接到 github.com 端口 443:连接被拒绝”