MobX:在执行 fetch 期间上下文丢失

huangapple go评论83阅读模式
英文:

MobX: context is lost during fetch execution

问题

在使用 ModX 编写 fetchPosts 方法时,我遇到一个与 fetchPosts 内部的 this 未定义相关的错误,尽管我使用了箭头函数。如何修复这个行为?

import { makeAutoObservable } from "mobx"

class Todo {
  todos = []

  constructor() {
    makeAutoObservable(this)
  }

  fetchTodos() {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((res) => res.json())
      .then((json) => this.todos.concat(json))
      .catch((e) => console.log(e))
  }
}

export default new Todo()

使用 Chrome DevTools,输出显示方法中的 this 变为未定义。

英文:

I am writing the fetchPosts method using ModX, but I get an error related to the fact that inside fetchPosts this is undefined, although I use the arrow function. How to fix this behavior?

import { makeAutoObservable } from "mobx"

class Todo {
  todos = []

  constructor() {
    makeAutoObservable(this)
  }

  fetchTodos() {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((res) => res.json())
      .then((json) => this.todos.concat(json))
      .catch((e) => console.log(e))
  }
}

export default new Todo()

using chrome devtools it is output that this in the method becomes undefined

答案1

得分: 0

由于您的函数不是箭头函数,并且您以这种方式传递它onClick={todo.fetchTodos},这与MobX或React无关,这只是Javascript的工作原理。

要修复它,您可以将其改为箭头函数:

class Todo {
  todos = []

  constructor() {
    makeAutoObservable(this)
  }

  // 在这里将其改为箭头函数
  fetchTodos = () => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((res) => res.json())
      .then((json) => this.todos.concat(json))
      .catch((e) => console.log(e))
  }
}
英文:

Context is lost because your function is not an arrow function and you pass it like that onClick={todo.fetchTodos}, it's not related to MobX or React, it's just how Javascript works

To fix it you can make it an arrow function:

class Todo {
  todos = []

  constructor() {
    makeAutoObservable(this)
  }

  // Make it an arrow function here
  fetchTodos = () => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((res) => res.json())
      .then((json) => this.todos.concat(json))
      .catch((e) => console.log(e))
  }
}

huangapple
  • 本文由 发表于 2023年6月5日 21:01:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76406688.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定