在Mobx中嵌套可观察对象可以吗?

时间:2018-09-29 12:16:40

标签: reactjs mobx

我是Mobx的新手,遇到了一些麻烦。

在Mobx中另一个可观测对象内部可以有一个观测对象吗?

我有一家商店:

class ObservableTasksStore {
  @observable
  tasks = [
    new Task(111, 'clean the car', 'with soap plz, it is really important', Duration(7, TIME.DAYS), Duration(6, TIME.MONTHS), '2018-08-17T10:02:18.674Z'),
    new Task(222, 'check car wheels', '', Duration(2, TIME.DAYS), Duration(1, TIME.MONTHS)),
    new Task(333, 'shinanint', ' check your teeth', Duration(2, TIME.DAYS), Duration(1, TIME.MONTHS))
  ]
  @action
   markTaskAsDone = (id) => {
     const index = this.tasks.findIndex((_tsk) => _tsk.id === id)
     this.tasks[index].markAsDone()
  }

但它不会在更改时调用渲染。

要渲染的类:

import React from 'react'
import { TaskCard } from '../TaskCard/TaskCard'
import { observer } from 'mobx-react'

const TasksList = ({taskStore}) => {///ObservableTasksStore passed as arg

  const tasks = taskStore.tasks

  return (
    tasks.map((task) => {

      return <TaskCard key={task.id}
                       id={task.id}
                       taskName={task.taskName}
                       description={task.description}
                       notifyDuration={task.notifyDuration}
                       recurring={task.recurring}
                       lastDone={task.lastDone}
                       daysLeft={task.daysLeft}
                       dueDate={task.dueDate}
      />
    })
  )
}

export default observer(TasksList)

仅当我将@observable添加到Task类时。

1。Task也具有@observable吗?

    export class Task {
      id;
      taskName;
      description;
      notifyDuration;
      recurring;
       @observable
      lastDone;
       @observable
      isActive;


 constructor (id, taskName, description, notifyDuration, recurring, lastDone, isActive) {
        this.id = id || uuidv4()
        this.taskName = taskName
        this.description = description
        this.notifyDuration = notifyDuration
        this.recurring = recurring
        this.lastDone = lastDone ? moment(lastDone) : undefined
        this.isActive = isActive || true
      }

      @action
      markAsDone () {
        this.lastDone = moment()
        this.isActive = false
      }
    }

问题是,当我添加mobx strict模式时,我有一个Maximum call stack size exceeded

index.module.js:768 Uncaught RangeError: Maximum call stack size exceeded
    at initializeInstance$$1 (mobx.module.js:275)
    at ObservableTasksStore.get [as tasks] (mobx.module.js:266)

知道为什么吗?

可在此处找到源: https://github.com/yuriabaev/taskScheduler/tree/mobx-nested-observable

1 个答案:

答案 0 :(得分:0)

对于您的情况,您必须在@observable类中使用Task,因为从类创建对象时,只有您指定为可观察的属性才是可观察的(即使您将它们推入可观察的属性也是如此)数组)。

要解决此问题,您应该执行以下操作:

configure({
  enforceActions: true
});

从mobx版本5.1.0开始,您应该这样使用它:

configure({
  enforceActions: 'observed'
});

因为要在构造函数中更新一个可观察的值,以获取更多信息:https://mobx.js.org/refguide/api.html#-enforceactions