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

Vue.js中axios请求.then回调不执行:如何触发成功提示?

问题解决办法

核心问题

你同时混用了async/await和.then/.catch,这会导致逻辑混乱;另外原代码中若请求失败时error.response.data.message不存在,会直接报错中断.catch内的代码执行,让你看不到错误提示。

修正方案

方案一:用async/await + try/catch统一处理(推荐)

这种写法逻辑更直观,避免链式调用的混乱:

methods: {
  async pay() {
    this.$notify(`working`);
    if (!this.$v.$invalid) {
      try {
        const data = {
          to: this.to,
          subject: this.subject,
        };

        // 等待请求完成
        await axios.post("http://localhost:4000/api/blogs", data);
        // 请求成功后执行通知
        this.$notify(`email has been sent`);
      } catch (error) {
        console.error('请求出错:', error);
        // 用可选链避免不存在属性导致的报错
        const message = error.response?.data?.message || '未知错误';
        this.$notify("Oh oo!", `${message}`, "error");
      }
    }
  }
}

方案二:只用.then/.catch(不使用async/await)

如果习惯链式调用,就彻底去掉async/await:

methods: {
  pay() {
    this.$notify(`working`);
    if (!this.$v.$invalid) {
      const data = {
        to: this.to,
        subject: this.subject,
      };

      axios.post("http://localhost:4000/api/blogs", data)
        .then(() => {
          this.$notify(`email has been sent`);
        })
        .catch(error => {
          console.error('请求出错:', error);
          const message = error.response?.data?.message || '未知错误';
          this.$notify("Oh oo!", `${message}`, "error");
        });
    }
  }
}

额外排查步骤

  1. 打开浏览器控制台的Network面板,查看这个POST请求的状态码:
    • 若为2xx状态码(比如200),说明请求成功,修正后的代码会触发成功通知;
    • 若为4xx/5xx状态码,说明请求失败,会进入错误处理分支,同时控制台会打印错误详情。
  2. 确认this.$notify的参数格式正确,避免因参数错误导致通知不显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:42:21