为什么 React 组件在用 observer() 包装时会渲染两次?

Why are React components rendering twice when wrapped with observer()?

简单地用 observer() 包装 React 组件似乎会导致它们渲染两次。可能的原因是什么?我是 运行 最新版本的 react 16.8.3、mobx 5.9.4 和 mobx-react-lite 1.2.0

例如:

import React from "react";
import { observer } from "mobx-react-lite";

const Item = observer(() => {
  return (
    <div>
      {console.log("render item")}
      Item
    </div>
  );
});

export default Item;

这是在一个相对复杂的应用程序中发生的。我在调试另一个问题时注意到了这种行为。然后,我删除了尽可能多的代码,并能够在一个非常简单的案例中重现该问题。

编辑:请参阅下面的答案。我能够通过尝试使用 codesandbox 进行回购来确定问题。

我应该完成 codesandbox I was working on before posting the question although this may save someone else the pain and wasted time. It turns out that the reason the double renders are occurring is because I'm using React.StrictMode. Interestingly, the double renders with React.StrictMode only seem to occur when the component is wrapped with observer() Here is the codesandboxReact.StrictMode 用于整个应用程序 (index.js),如果删除,双重渲染将停止。