首页 > 解决方案 > 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);
            });
        },

标签: javascriptvue.js

解决方案


看起来你很接近。

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);
            });
        },

推荐阅读