this.hasErrors不是函数

this.hasErrors is not a function

本文关键字:函数 hasErrors this      更新时间:2023-10-17

我在网上寻找问题的解决方案,但找不到合适的答案。尽管网上有很多这样的问题。

在我的打字脚本文件中,我有以下三种方法:

hasErrors() {
    // Checking for errors
}
saveItem() {
    if (this.hasErrors())
        return;
    // Save item
}
sendItemToAuthority() {
    if (this.hasErrors())
        return;
    // Send item to authority
}

不知何故,sendItemToAuthority()内部的this.hasErrors()没有被识别为函数,但在saveItem()中,它可以毫无问题地工作。我在chrome开发工具中得到以下错误:

this.hasErrors不是的函数

我发现以下可能性也不适用于我(相同的错误消息):

sendItemToAuthority() {
    var self = this;
    if (self.hasErrors)
        return;
    // Send item to authority
}

有人能给我一个解决方案吗?我真的不明白为什么它不起作用。

saveItem()可以正常工作。我在chrome开发工具中得到以下错误this.hasErrors不是一个函数

你很可能有错误的this。使用arrrow函数:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

我终于找到了解决方案。在我的构造函数中,我有

this.saveItem = this.saveItem.bind(this);

但忘记添加

this.sendItemToAuthority = this.sendItemToAuthority.bind(this);