在React Native应用中获取请求后,MobX存储不会更新

时间:2019-08-19 14:47:41

标签: javascript react-native react-hooks mobx mobx-react

我创建了一个具有异步提取功能的MobX存储。当我调用它时,我从API获取数据。我在控制台中检查了数据,每次都来了,但是MobX存储并没有改变它。你能告诉我如何解决吗?

MobX商店:

import { createContext } from 'react'
import { action, decorate, observable, computed, runInAction } from 'mobx'
import mapObjects from '../utils/mapObjects'

export class DataStore {
  data = null
  error = false
  loading = true


  async fetchData(url) {
    this.data = null
    this.loading = false
    try {
      console.log('TRY')
      const response = await fetch(url)
      const jsonResponse = await response.json()
      const obj = await mapObjects(jsonResponse)
      runInAction(() => {
        console.log('WRITE!!!')
        this.loading = false
        this.data = obj
      })
    } catch (err) {
      runInAction(() => {
        console.log(err)
        this.loading = false
        this.error = err
      })
    }
  }
}

decorate(DataStore, {
  data: observable,
  error: observable,
  loading: observable,
  fetchData: observable
})

export default createContext(new DataStore())

1 个答案:

答案 0 :(得分:1)

在您的decorate(...)通话中,您将fetchData设为observable,而不是action