上传图片至Firebase Storage后赋值userPhoto报Cannot set properties of undefined错误
问题根因
你遇到的TypeError: Cannot set properties of undefined (setting 'userPhoto')报错是this指向异常导致的:
你在pictureRef.put(imageData).then()的回调中使用了普通函数function () {}声明,普通函数的this会绑定到执行时的上下文,此处回调执行时没有绑定外层的组件实例,因此this值为undefined,无法访问到组件上的userPhoto属性。你下方注释的Firestore数据库更新代码也存在同样的this指向问题。
解决方案
有三种常用的修复方式,推荐优先使用第一种:
方式1:将普通回调函数替换为箭头函数(最优)
箭头函数不会生成独立的this绑定,会自动继承外层作用域的this值,此处外层作用域的this就是当前组件实例,直接访问即可。
修改后的storeImage函数示例:
async storeImage(imageData: any, location: string) { try { const imageName = this.imageName(); return new Promise((resolve, reject) => { const pictureRef = this.angularFireStorage.ref(location + imageName); pictureRef .put(imageData) // 把普通function回调替换为箭头函数 .then(() => { pictureRef.getDownloadURL().subscribe((url: any) => { resolve(url); console.log(url); this.userPhoto = url; // 下方注释的更新代码也可以正常执行了 this.afs.collection('user').doc(this.userId).set({ 'userPhoto': url, 'editedAt': Date.now() }, {merge: true}) }); }) .catch((error) => { reject(error); }); }); } catch (e) {} }
方式2:提前在外层保存组件实例引用
在Promise逻辑开始前先把当前组件的this存到临时变量中,回调中直接使用该临时变量访问属性:
async storeImage(imageData: any, location: string) { try { // 提前保存组件实例的this引用 const that = this; const imageName = this.imageName(); return new Promise((resolve, reject) => { const pictureRef = this.angularFireStorage.ref(location + imageName); pictureRef .put(imageData) .then(function () { pictureRef.getDownloadURL().subscribe((url: any) => { resolve(url); console.log(url); // 使用保存的that访问组件属性 that.userPhoto = url; that.afs.collection('user').doc(that.userId).set({ 'userPhoto': url, 'editedAt': Date.now() }, {merge: true}) }); }) .catch((error) => { reject(error); }); }); } catch (e) {} }
方式3:给普通回调函数绑定this
通过bind()方法手动把回调函数的this绑定到当前组件实例:
pictureRef .put(imageData) .then(function () { // 内部逻辑不变 }.bind(this)) // 手动绑定当前组件的this .catch((error) => { reject(error); });
内容的提问来源于stack exchange,提问作者user13410056
相关产品推荐
相关产品推荐

