【问题标题】:TypeError: Cannot read property 'currentQuestions' of undefined in TypeScriptTypeError:无法读取 TypeScript 中未定义的属性“currentQuestions”
【发布时间】:2019-03-31 14:34:10
【问题描述】:

我有以下代码,我想做的是从数据库中获取一些数据(这似乎是成功的,我试图记录它),然后排列这些数据并发送一个数组作为响应。我的班级:

export class Controller {

    currentQuestions: IQuestionArranged[] = []; // This should be my array that I am trying to send as response

    constructor(){ }

    public async startNewGame(req: express.Request, res: express.Response): Promise<void> {
        let factory: RepositoryFactory = new RepositoryFactory();
        let repository: RepositoryInterface = factory.createRepository();

        let questionsFetched: IQuestionFetched[] = await repository.fetchQuestions();    // array of questions as they were fetched
        // let currentQuestions: IQuestionArranged[] = []; // <<<<<

        // forEach through fetched questions to arrange them
        questionsFetched.forEach(currentQuestion => {
            // check if the current question already exists in the array
            if (this.currentQuestions.filter(e => e.id == currentQuestion.questionId).length != 0) {
                // if yes -> find the question and add the new answer with its id
                this.currentQuestions
                    .filter(e => e.id == currentQuestion.questionId)
                    .map(e => e.answers.push({
                        id: currentQuestion.answerId,
                        answer: currentQuestion.answer
                    }));
            } else {
                // if no -> add the new question with the new answer
                this.currentQuestions.push({
                    id: currentQuestion.questionId,
                    question: currentQuestion.question,
                    answers: [{
                        id: currentQuestion.answerId,
                        answer: currentQuestion.answer
                    }]
                });
            }
        });
        res.send(this.currentQuestions);
    }
}

但是我收到了这个错误,上面写着“UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'currentQuestions' of undefined”(完整的错误描述 here)。如果我使用局部变量(标有 5 个左箭头作为注释的变量)而不是类属性,它似乎工作得很好,这让我觉得我没有正确使用它,但我不知道我的错误在哪里...

【问题讨论】:

  • 您正在寻求调试帮助,即not a proper problem statement。要回答您的隐含问题,您可以通过将您的上下文(即调用 startNewGameController 实例)作为第二个参数 (see here) 来修复 Array.forEach 中的 this

标签: javascript typescript express oop


【解决方案1】:

你能用函数表达式试试箭头函数吗?例如 =>

public startNewGame = async (req: express.Request, res: express.Response) => {
 // Your code goes here.
}

【讨论】:

  • 谢谢您,先生。这实际上解决了我的问题。虽然我仍然不明白为什么我的示例失败了,这绝对让我发疯......无论如何,再次感谢:)
  • 问题与“this”变量的上下文有关。箭头函数没有它自己的“this”。他们使用封闭词法范围的“this”值。
【解决方案2】:

我找到了一个更清洁的解决方案。我必须做的是像这样绑定“this”变量:

constructor() {
   this.startNewGame = this.startNewGame.bind(this);
}

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 2017-11-02
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2018-08-16
    • 2018-02-12
    • 2021-07-09
    • 2021-10-31
    相关资源
    最近更新 更多