英文:
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))
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论