You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向Vuex Action传递回调函数?回调提前执行问题如何解决

问题原因

  • 回调函数传递时加了括号,导致函数被立即执行:你在传递confirmCallback、rejectCallback时写的是this.onModalOpen(),JS会直接执行该函数,将返回值(此处为undefined)传递给Vuex,而非传递函数本身。
  • Vuex Action仅支持接收单个payload参数:你定义test action时写了3个入参,实际调用时传入的对象只会被第二个参数接收,第三个及之后的参数永远为undefined,根本无法获取到reject回调。

修正后的代码

src/store/modules/web3.module.js

import Web3 from "web3";

const state = {};

const getters = {};

const mutations = {};

const actions = {
  // 从第二个payload参数中解构出两个回调
  async test(context, { confirmCallback, rejectCallback }) {
    confirmCallback();
    rejectCallback();
  }
};

export default {
  state,
  getters,
  actions,
  mutations
};

App.vue

<template>
  <div id="app"></div>
</template>

<script>
import { mapActions } from "vuex";

export default {
  name: "App",
  methods: {
    ...mapActions(["test"]),
    onModalOpen() {
      console.log("open");
    },
    onModalClose() {
      console.log("Close");
    },
  },
  async created() {
    // 传递函数本身,不要加括号执行
    let result = await this.test({
      confirmCallback: this.onModalOpen,
      rejectCallback: this.onModalClose,
    });
  },
};
</script>

内容的提问来源于stack exchange,提问作者CCCC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:06:09