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

调用支付组件时出现this.pay() is not a function错误的排查求助

问题原因及解决方案

核心原因

在openWidget方法里,OnTransactionCompleted使用了普通function作为回调函数,此时函数内部的this指向的是PaytureWidget的实例,而不是你的组件实例。组件的pay()方法挂载在组件实例上,所以这里调用this.pay()会提示“不是函数”。

修复方案

有三种常用的解决方式:

1. 使用箭头函数(推荐)

箭头函数不会改变this的指向,它会继承外层作用域的this(即组件实例):

openWidget() {
  // @ts-ignore
  let widget = new PaytureWidget({
    Key : "Merchant",
    Amount : this.model.sum,
    Product : "Payment №1",
    Domain : 2,
    OnTransactionCompleted : (success: any) => { 
      this.pay()
    }
  })
}

2. 提前保存组件的this

在回调函数外部把组件实例的this存入变量,在回调内使用该变量调用方法:

openWidget() {
  const that = this; // 保存组件实例的this
  // @ts-ignore
  let widget = new PaytureWidget({
    Key : "Merchant",
    Amount : this.model.sum,
    Product : "Payment №1",
    Domain : 2,
    OnTransactionCompleted : function(success: any) { 
      that.pay()
    }
  })
}

3. 用bind绑定this

给回调函数绑定组件实例的this,强制修正它的指向:

openWidget() {
  // @ts-ignore
  let widget = new PaytureWidget({
    Key : "Merchant",
    Amount : this.model.sum,
    Product : "Payment №1",
    Domain : 2,
    OnTransactionCompleted : function(success: any) { 
      this.pay()
    }.bind(this)
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:05:26