2016-05-31 21 views
11

私はMobX 2.2.2を使用して、非同期アクション内で状態を変更しようとしています。私はMobXのuseStrictをtrueに設定しました。async関数と.thenとのMobX @actionデコレータの使用

@action someAsyncFunction(args) { 
    fetch(`http://localhost:8080/some_url`, { 
    method: 'POST', 
    body: { 
     args 
    } 
    }) 
    .then(res => res.json()) 
    .then(json => this.someStateProperty = json) 
    .catch(error => { 
    throw new Error(error) 
    }); 
} 

私が取得:

Error: Error: [mobx] Invariant failed: It is not allowed to create or change state outside an `action` when MobX is in strict mode. Wrap the current method in `action` if this state change is intended 

は、私は2番目の.then書に@actionデコレータを供給する必要がありますか?どんな助けもありがとう。

答えて

17

2番目の.thenステートメントに@actionデコレータを指定する必要がありますか?どんな助けもありがとう。

これは実際の解決策にかなり近いです。

.then(json => this.someStateProperty = json) 

.then(action(json => this.someStateProperty = json)) 

@actionに排他的ではありません多くの方法で呼び出すことができます覚えactionしてくださいする必要があります。 the docs on actionから:

  • action(fn)
  • action(name, fn)
  • @action classMethod
  • @action(name) classMethod
  • @action boundClassMethod = (args) => { body }
  • @action(name) boundClassMethod = (args) => { body }

です関数をアクションとしてマークする有効な方法です。ここで

は、ソリューションを実証ビンです:あなたのエラーは、実際に私がトップレベル@actionを再帰的にそれが飾っています関数の内部アクションとして任意の関数を飾るないことを推測しているなぜ起こるかについてはhttp://jsbin.com/peyayiwowu/1/edit?js,output

mobx.useStrict(true); 
const x = mobx.observable(1); 

// Do async stuff 
function asyncStuff() { 
    fetch('http://jsonplaceholder.typicode.com/posts') 
    .then((response) => response.json()) 
    // .then((objects) => x.set(objects[0])) BREAKS 
    .then(mobx.action((objects) => x.set(objects[0]))) 
} 

asyncStuff() 

、あなたの無名関数があなたの約束に渡されたことが実際にはactionではないことを意味します。

+1

非同期/待つでこれを行うにはどのように? – TangMonk

8

上記の答えを補完する。実際にはactionは、渡す関数上でのみ動作します。 thenの機能は別々のスタック上で実行されるため、別々のアクションとして認識する必要があります。あなたがそれらを使用する場合は簡単にデベロッパーツールでそれらを認識するようにあなたも、同様の操作に名前を付けることができ

注:

then(action("update objects after fetch", json => this.someStateProperty = json))

+0

"以下は" * now: 'と答えています。(lol – m0meni

+0

あなたの答えは完全なものです。補足物語のために次回コメントを使用します.. – mweststrate

+0

@ AR7を正しいものとしてマークして修正しました:) – twsmith

関連する問題