使用 Mobx 时如何解决 `reaction is not defined`?

How to solve `reaction is not defined` when using Mobx?

我是 React 和 Mobx 的新手,正在学习在线教程。

教程说要使用 reaction 例如:

reaction(() => list.totalPrice, () => changed++)

但我只是得到错误 ReferenceError: reaction is not defined

我不确定这意味着什么或如何让它发挥作用(在 Google 或 SO 上找不到任何相关信息)。

根据 Mobx 文档,我似乎正确使用了它 https://mobx.js.org/refguide/reaction.html

有人知道这是什么意思吗?

我的完整代码是:

import { getSnapshot, onSnapshot, onPatch } from "mobx-state-tree"
import { WishList, WishListItem } from "./WishList"

it("can create a new instance of a model", () => {
  const item = WishListItem.create({
    name: "some item name",
    price: 28.74,
  })

  expect(item.price).toBe(28.74)
  expect(item.image).toBe("")
  item.changeName("Narnia")
  expect(item.name).toBe("Narnia")

})

it("can create a wishlist", () => {
  const list = WishList.create({
    items: [
      {
        name: "another item name",
        price: 30.43
      } 
    ]
  })

  expect(list.items.length).toBe(1)
  expect(list.items[0].price).toBe(30.43)
})

it("can add new item to list", () => {
  const list = WishList.create()
  const states = []
  onSnapshot(list, snapshot => {
    states.push(snapshot)
  })

    list.add({
      name: "A new item",
      price: 10
    }
  )

  expect(list.items.length).toBe(1)
  expect(list.items[0].name).toBe("A new item")
  list.items[0].changeName("Hello world")
  expect(list.items[0].name).toBe("Hello world")

  expect(getSnapshot(list)).toMatchSnapshot()

  expect(states).toMatchSnapshot()

})


// Patches
it("can add new item to list - 2", () => {
  const list = WishList.create()
  const patches = []
  onPatch(list, patch => {
    patches.push(patch)
  })

    list.add({
      name: "A new item",
      price: 10
    }
  )

  list.items[0].changeName("Hello world 2")

  expect(patches).toMatchSnapshot()

})

// Views
it("can calculate the total price of a wishlist", () => {
  const list = WishList.create({
    items: [
      {
        name: "Machine gun preacher",
        price: 11,
        image: ""
      },
      {
        name: "lego",
        price: 100,
        image: ""
      }
    ]
  })

  expect(list.totalPrice).toBe(111)

  let changed = 0
  reaction(() => list.totalPrice, () => changed++)

  expect(changed).toBe(0)
  console.log(list.totalPrice)
  list.items[0].changeName("test")
  expect(changed).toBe(0)
  list.items[0].changePrice(10)
  expect(changed).toBe(1)

})

教程排除了关于添加的部分

import { reaction } from "mobx"