Search code examples
mobx

MobX: context is lost during fetch execution


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


Solution

  • 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))
      }
    }