TypeError: Cannot read properties of undefined (reading '$modal')

原代码:

复制代码
    handleFinish(row) {this.$modal
        .confirm('确认录取学生编号为"' + row.stuCode + '"的成绩?')
        .then(function () {
          finishStudentScore({ id: row.id }).then((response) => {
            if (response.code == 200) {
              this.$modal.msgSuccess("提交成功");
              this.open = false;
              this.getList();
            }
          });
        })
        .catch(() => {});
    }
复制代码

在JavaScript中,this关键字指向当前执行上下文的对象。在Vue.js中,this通常指向当前Vue实例
在上面的代码中,this引用了当前Vue实例,但是,在then回调函数内部,this的值可能会发生变化,不再指向Vue实例。

解决办法

法一:使用中间变量保存当前实例
为了避免这种情况,可以创建一个名为selfThis的变量,并将其赋值为this,以保存当前Vue实例的引用。使用selfThis可以确保在后续能够正常访问和使用Vue实例的属性和方法,即使this的值发生了改变。在异步操作中特别有用,因为异步操作的执行上下文可能与定义时的上下文不同。

复制代码
   handleFinish(row) {
    let selfThis= this; this.$modal .confirm('确认录取学生编号为"' + row.stuCode + '"的成绩?') .then(function () { finishStudentScore({ id: row.id }).then((response) => { if (response.code == 200) { selfThis.$modal.msgSuccess("提交成功"); selfThis.open = false; selfThis.getList(); } }); }) .catch(() => {});
  }
复制代码

法二:利用箭头函数解决(推荐)
在箭头函数中,this 指向的是定义时所在的上下文,而不是执行时所在的上下文。因此,使用箭头函数来定义 then 回调函数,可以避免 this 值的变化问题,也就不需要使用中间变量selfThis

复制代码
    handleFinish(row) {
      this.$modal
        .confirm('确认录取学生编号为"' + row.stuCode + '"的成绩?')
        .then( () => {
          finishStudentScore({ id: row.id }).then((response) => {
            if (response.code == 200) {
              this.$modal.msgSuccess("提交成功");
              this.open = false;
              this.getList();
            }
          });
        })
        .catch(() => {});
    }
复制代码

 



 

posted @   游戏三昧的木笔  阅读(412)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示