为什么我们不能在 mobx-react 中使用 React.useMemo 来保持对状态对象的引用?

Why can't we use React.useMemo in mobx-react to keep reference to the state object?

目前我的项目仍在使用 mobx@4 和 mobx-react@6,我在文档中发现了这个警告:

公平警告。永远不要使用 React.useMemo 来保持对状态对象的引用。它可能会被 React 随机丢弃,你可能会丢失数据。(mobx-react documentation)

看不懂,谁能帮忙举个例子说明一下原因?

引用自 React 文档:

You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.

基本上,如果 React 愿意,它可以随时重新实例化 memoized 值,你将失去整个 Store,因为它将使用默认参数重新创建。

它现在可能不会这样做,但最好不要将 memo 用于持久值,这样如果你迁移到 React 的未来版本,你就不会被迫进行重构。

Link: https://reactjs.org/docs/hooks-reference.html#usememo