Angular集成Stripe JS时paymentMethod回调内无法调用自定义方法问题
问题原因
你遇到的报错本质是普通函数回调的this指向丢失问题:
你在paymentRequest.on的事件回调、stripe.confirmCardPayment的then回调中全部使用了普通function声明,普通函数的this会根据执行上下文动态绑定,在Stripe触发回调、Promise异步执行回调时,执行上下文已经不再是你的Angular组件实例,此时this取值为undefined,自然无法读取挂载在组件实例上的completePaymentInOrder方法。
同时你的completePaymentInOrder内部用到的this.orderid、this.http、this.apiKey也同样依赖组件实例的正确this指向,必须先修复回调的this指向才能正常运行。
解决方法
有三种常用的修复方案,优先推荐第一种:
方案1:将所有普通回调替换为箭头函数(最常用)
箭头函数不会创建自身的this,会直接继承外层作用域的this,天然保持和组件实例的绑定,修改后的代码示例:
paymentRequest.on('paymentmethod', (ev) => { console.log(ev.paymentMethod.id); const clienSecret = dataset.secret stripe.confirmCardPayment( clienSecret, {payment_method: ev.paymentMethod.id}, {handleActions: false} ).then((confirmResult) => { if (confirmResult.error) { alert('Transaktion fehlgeschlagen'); ev.complete('fail'); } else { ev.complete('success'); if (confirmResult.paymentIntent.status === 'requires_action') { stripe.confirmCardPayment(clienSecret).then((result) => { if (result.error) { alert('Bezahlung fehlgeschlagen') } else { this.completePaymentInOrder(); console.log('payment succeeeded'); } }); } else { this.completePaymentInOrder(); console.log('payment succeeded'); } } }); });
方案2:提前缓存组件实例的this引用
如果不想修改原有函数写法,可以在回调最外层提前把组件实例的this存到临时变量中,后续用临时变量调用方法:
const componentThis = this; // 在外层提前缓存组件实例 paymentRequest.on('paymentmethod', function (ev) { console.log(ev.paymentMethod.id); const clienSecret = dataset.secret stripe.confirmCardPayment( clienSecret, {payment_method: ev.paymentMethod.id}, {handleActions: false} ).then(function (confirmResult) { if (confirmResult.error) { alert('Transaktion fehlgeschlagen'); ev.complete('fail'); } else { ev.complete('success'); if (confirmResult.paymentIntent.status === 'requires_action') { stripe.confirmCardPayment(clienSecret).then(function (result) { if (result.error) { alert('Bezahlung fehlgeschlagen') } else { // 用缓存的componentThis调用组件方法 componentThis.completePaymentInOrder(); console.log('payment succeeeded'); } }); } else { // 用缓存的componentThis调用组件方法 componentThis.completePaymentInOrder(); console.log('payment succeeded'); } } }); });
方案3:用bind方法手动绑定this
给每个普通回调函数末尾添加.bind(this),手动将回调的this固定为当前组件实例:
paymentRequest.on('paymentmethod', function (ev) { // 原有逻辑不需要修改 }.bind(this)); // 给回调绑定组件实例的this
内容的提问来源于stack exchange,提问作者Dominik Hartl
相关产品推荐
相关产品推荐

