简体   繁体   中英

Vuex3 mutation doesn't work when committed the then() of a promise

I have a vuex store that looks like this:

new Vuex.Store({
    state: {
        foo: "initial value"
    },
    mutations: {
        update_foo (state, payload) {
            state.foo = payload;
        }
    },
    actions: {
        update (context) {
            context.commit("update_foo", "bar");
            APIwrapper("api url to get data")
                .then(response => context.commit("update_foo", "not bar"))
                .catch(e => console.error(e));
        }
    }
}

When I store.dispatch('update') from my vue instance, it faithfully mutates foo to be "bar". Once the APIwrapper promise does it's thing, the update_foo mutation is called, dumping out the store shows that state.foo equals "not bar", but that change is not reflected in my template.

I am not super wild about re-writing my api wrapper object. Is there any particular reason why this doesn't work and is there a work around?

EDIT: Here's the rest of my setup.

Template looks like this:

<div>
    <i :foo="foo" v-html="foo"></i>
</div>

And my vue instance looks like:

new Vue({
    store,
    el: '#selector',
    template: template,
    beforeCreate: function () {
        store.dispatch('update');
    },
    computed: {
        foo: () => store.state.foo,
    },
});

With some brainstorming help, I managed to root out the problem. I had two Vue instances on the page that, through shared base classes, were using a common variable to store the instance. So, the one was overwriting the other. The instantaneous mutations worked because the instance still existed, but by the time the API responded, the instance had been overwritten and the update was failing.

Sloppy on my part. Thanks for everyone's time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM