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

发布时间 2023-11-29 11:31:42作者: 游戏三昧的木笔

原代码:

    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(() => {});
    }