簡體   English   中英

垃圾回收如何解決mobx-utils中的異步操作?

[英]How does garbage collection address async actions in mobx-utils?

我想創建存儲明確方法,當我知道新的業務數據是可用的(像我可以刷新lazyObservablemobx-utils ),但容易被附加更多的計算值和行動功能。

從create-react-app開始,使用此index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {observable} from 'mobx';
import {observer} from 'mobx-react';
import {asyncAction} from 'mobx-utils';

const flipACoin = () => Math.random() > 0.5;

function determineGodliness() {
  const screwYourRAM = new Array(1000000).fill(Math.random());

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([flipACoin(), flipACoin()]);
    }, 1500);
  });
}

function godStore() {
  const store = observable({
    alpha: false,
    omega: false,
    waiting: false,
    refresh: asyncAction(function *() {
      this.waiting = true;
      [this.alpha, this.omega] = yield determineGodliness();
      this.waiting = false;
    }),
    get isGod() {
      return this.alpha && this.omega;
    }
  });

  store.refresh();

  return store;
}

window.store = godStore();

const App = observer(({store}) => <p>{
  (store.waiting)
    ? 'The suspense is killing me!'
    : (store.isGod)
      ? 'I am the Alpha and the Omega'
      : 'I just work here.'
}</p>);

ReactDOM.render(<App store={window.store} />, document.getElementById('root'));

每次在控制台中運行window.store.refresh() ,任務管理器都會顯示內存使用量的增加。 有趣的是,使用setInterval(window.store.refresh, 3000)實際上會引起內存使用的波動,而不是線性上升。 在這兩種沖突的情況之間,我對垃圾收集器如何看待此設置感到困惑。

我應該怎么做才能絕對確定screwYourRAM最終會被垃圾回收? 我所關心的只是生成器返回的內容,而不是過渡期間分配的內容。

僅通過查看內存圖很難確定內存泄漏。 除非確實存在短缺,否則Afaik V8不會總是釋放所有內存(畢竟,GC-ing是一項優化,過度收集將節省內存,但是會消耗過多的CPU周期。您不能假設afaik認為空閑的VM會自動釋放所有內存)。 因此,我通常使用節點腳本進行測試,該腳本可以長時間運行並重復一個過程,並使用有限的內存來查看是否確實泄漏了某些內容。

在您的示例中,據我所知/可以告訴我們的,沒有任何理由會導致內存泄漏。 在某些時候,Promise是gc-ed的,因此可以gc隨附它的閉包。 chrome控制台會通過$_保留對您的承諾的引用,這樣也可以解釋內存的增加)

要正確查看是否存在內存泄漏,請使用chrome / firefox中的事件探查器,並確保您強制執行GC(chrome devtools有一個用於執行此操作的按鈕,也許還有FF)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM