首页 > 解决方案 > MobX 不会在 fetch promise 回调中更新 react DOM

问题描述

我正在尝试通过在反应打字稿应用程序的 fetch 回调中更改可观察的 mobx 变量来更新反应 dom,但 mobx 对变量更改没有显示任何反应。我这样定义我的变量:

@observable  data:any = []

并在我的构造函数中更改数据值:

 constructor(){
        this.data.push(
            {
                count:0,
                dateTime:'2017'
            })
        this.getData();
    }

它工作正常并按预期正确更新 dom。在getData()方法中,我编写了一个 fetch 从服务器检索数据:

@action getData(){
   this.data.push(
     {
      count:1,
      dateTime:'2018'
     })
    fetch(request).then(response=>response.json())
    .then(action((data:Array<Object>)=>{
        this.data.push(data)
        console.log(data)
    }));
}

所以我的视图现在显示 2 值 2017 和 2018 对象数据,但我从服务器获得的 2019 数据没有显示。日志显示正确的值和以正确方式填充的变量,但是在我在 fetch 函数回调中设置任何变量后,mobx 不更新视图,我不知道为什么?ps:我在 ECMA 中做同样的事情,没有问题,但在 typescript mobx 中的行为不同

标签: reactjstypescriptmobxmobx-react

解决方案


检查我的方法:

import { action, observable, runInAction } from 'mobx'

class DataStore {
  @observable data = null
  @observable error = false
  @observable fetchInterval = null
  @observable loading = false

  //*Make request to API
  @action.bound
  fetchInitData() {
    const response = fetch('https://poloniex.com/public?command=returnTicker')
    return response
  }

  //*Parse data from API
  @action.bound
  jsonData(data) {
    const res = data.json()
    return res
  }

  //*Get objects key and push it to every object
  @action.bound
  mapObjects(obj) {
    const res = Object.keys(obj).map(key => {
      let newData = obj[key]
      newData.key = key
      return newData
    })
    return res
  }

  //*Main bound function that wrap all fetch flow function
  @action.bound
  async fetchData() {
    try {
      runInAction(() => {
        this.error = false
        this.loading = true
      })
      const response = await this.fetchInitData()
      const json = await this.jsonData(response)
      const map = await this.mapObjects(json)
      const run = await runInAction(() => {
        this.loading = false
        this.data = map
      })
    } catch (err) {
      console.log(err)
      runInAction(() => {
        this.loading = false
        this.error = err
      })
    }
  }

  //*Call reset of MobX state
  @action.bound
  resetState() {
    runInAction(() => {
      this.data = null
      this.fetchInterval = null
      this.error = false
      this.loading = true
    })
  }

  //*Call main fetch function with repeat every 5 seconds
  //*when the component is mounting
  @action.bound
  initInterval() {
    if (!this.fetchInterval) {
      this.fetchData()
      this.fetchInterval = setInterval(() => this.fetchData(), 5000)
    }
  }

  //*Call reset time interval & state
  //*when the component is unmounting
  @action.bound
  resetInterval() {
    if (this.fetchInterval) {
      clearTimeout(this.fetchInterval)
      this.resetState()
    }
  }
}

const store = new DataStore()
export default store


推荐阅读