Angular HttpClient调用报错:TypeError: 无法读取undefined的get属性
问题:Angular中Stripe回调内调用HttpClient报错"TypeError: Cannot read properties of undefined (reading 'get')"
问题详情:
- 模块已正确导入
HttpClientModule:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { IonicModule } from '@ionic/angular'; import { FormsModule } from '@angular/forms'; import { HomePage } from './home.page'; import { ReactiveFormsModule } from '@angular/forms'; import { HomePageRoutingModule } from './home-routing.module'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, HomePageRoutingModule, HttpClientModule, ReactiveFormsModule ], declarations: [HomePage] }) export class HomePageModule {}
- 组件已正确导入并注入
HttpClient:
import { HttpClient } from '@angular/common/http'; constructor(private http: HttpClient, private navCtrl: NavController) { Stripe.initialize({ publishableKey: 'private_key_im_using', }); }
- 直接调用
this.http正常,但在StripeCheckout的token回调中调用时触发错误,错误栈显示this.http未定义 - 服务端接口无问题,用VSCode HTTP客户端可正常访问
核心原因:
传统function定义的回调会改变this的上下文,此时回调内的this指向Stripe的回调执行环境,而非Angular组件实例,因此无法访问组件中注入的http对象。
解决方案:
方案1:使用箭头函数(推荐)
箭头函数会继承外部作用域的this,确保回调内的this指向组件实例:
pay(amount: any) { var handler = (<any>window).StripeCheckout.configure({ key: 'private_key_im_using', locale: 'auto', token: async (token: any) => { // 替换为箭头函数 console.log(token); this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe((response: any) => { console.log(response); }); } }); handler.open({}); }
方案2:提前保存组件的this引用
在pay函数内先将组件实例的this保存到变量中,回调内使用该变量访问组件属性:
pay(amount: any) { const componentThis = this; // 保存组件实例的this var handler = (<any>window).StripeCheckout.configure({ key: 'private_key_im_using', locale: 'auto', token: async function (token: any) { console.log(token); componentThis.http.get('https://jsonplaceholder.typicode.com/posts').subscribe((response: any) => { console.log(response); }); } }); handler.open({}); }
额外提示:
loadStripe方法内的token回调也存在相同的this指向问题,如果后续需要在该回调中调用组件属性,建议同样采用上述两种方法修正。
内容的提问来源于stack exchange,提问作者Hector_o'lector
相关产品推荐
相关产品推荐

