【问题标题】:Vuex this.$store undefined in "mounted" life cycle hookVuex this.$store 在“挂载”生命周期钩子中未定义
【发布时间】:2019-10-01 12:24:00
【问题描述】:

我目前正在将 Paypal 服务集成到我的 Vue 项目中。我参考了官方文档并复制了代码https://developer.paypal.com/docs/checkout/integrate/#6-verify-the-transaction。我能够呈现 Paypal 按钮,完成交易并收到一个 orderID。但是,由于以下错误,我无法将 orderID 发送到我的服务器:this.$store 未定义。 请注意,我可以在我的其他组件中引用 this.$store。以下是我的以下代码:

更新:我尝试在 onApprove 方法中使用 console.log(this),但它返回未定义。是这个问题吗?

更新 我已将 OnApprove 方法和 capture() 方法转换为箭头函数并收到不同的错误消息 this.$store.dispatch(...).then(...) .err 不是函数

更新我设法通过将 .err() 更改为 .catch() 来修复上述错误。

更新 我遇到了另一个问题,有时我单击 Paypal 按钮,外部 Paypal 窗口会立即自行关闭。我必须点击按钮几次,以防止这种奇怪的行为。我去了控制台日志,发现这条消息如下面的屏幕截图所示。

    <template>
  <div>
    <div id="paypal-button-container"></div>
  </div>
</template>

<script>
import { PRODUCT_PAYPAL } from "@/store/actions/products";

export default {
  mounted() {
    paypal
      .Buttons({
        createOrder: function(data, actions) {
          return actions.order.create({
            purchase_units: [
              {
                amount: {
                  value: "0.01"
                }
              }
            ]
          });
        },
         onApprove: (data, actions) => {
          return actions.order.capture().then(details => {
            alert("Transaction completed by " + details.payer.name.given_name);
            console.log("orderID is ");
            console.log(data.orderID);

            // Call your server to save the transaction
            return this.$store
              .dispatch(PRODUCT_PAYPAL, data.orderID)
              .then(() => {
                alert("success");
              })
              .catch(() => {
                alert("error");
              });
          });
        }
      })
      .render("#paypal-button-container");
  }
};
</script>

<style>
</style>

如下图所示,我收到了orderID,表示交易成功。但是, this.$store 是未定义的。因此,我无法将订单 ID 发送到我的服务器

【问题讨论】:

    标签: javascript vue.js paypal vuex


    【解决方案1】:

    在回调函数上使用箭头函数,以访问 this

    onApprove: (data, actions) => ...
    
    return actions.order.capture().then((details) => ...
    

    【讨论】:

    • 嗨@Kris!感谢您的回复,我已将其转换为箭头功能,现在收到不同的错误消息。这是消息:this.$store.dispatch(...).then(...).err 不是函数
    • @Issaki 将 err() 更改为 catch()
    • 所以不是 .err(() => { alert("error"); });你有 ".catch(() => { alert("error"); });"
    • 嗨@Kris!现在我收到了另一条错误消息:未找到状态(404)。我相信这与我的 API 路径有关,所以我会尝试修复它。最后一个问题,有时我点击 Paypal 按钮,外部的 paypal 窗口会立即自行关闭。我必须点击按钮几次,以防止这种奇怪的行为。我去了控制台日志,发现这条消息 Uncaught Error: Order Api response error: "name": "AUTHENTICATION_FAILURE", "message": "Authentication failed due to invalid authentication credentials. 我将编辑这篇文章以截图错误跨度>
    • 这与您的 API 有关,是的。既然来电了。抱歉,我不熟悉 PayPal API,我无法为您提供帮助。如果您的问题得到解答,请考虑将我的评论标记为答案;)
    猜你喜欢
    • 1970-01-01
    • 2019-12-29
    • 2018-08-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 2022-01-24
    相关资源
    最近更新 更多