报错TypeError: Cannot read properties of undefined (reading 'authService')求助
问题分析与解决:TypeError: Cannot read properties of undefined (reading 'authService')
错误原因
你在.then()回调中使用了传统的function(doc)写法,这种函数会创建独立的上下文,导致内部的this不再指向当前类的实例,而是指向回调函数自身的执行环境,因此this.authService会被判定为undefined,触发报错。
解决方案
1. 替换回调为箭头函数
箭头函数不会改变this的指向,会继承外部上下文的this,这样就能正确访问类实例的authService属性。
2. 统一使用await简化异步逻辑
你的代码混合了await和.then()写法,改用纯await风格可以让异步代码更易读,同时避免res.from/res.to变成未解析的Promise。
修改后的代码示例
优化getQuestion方法
async getQuestion(id: string): Promise<Question | null> { try { const doc = await this.db.collection("questions").doc(id).ref.get(); if (doc.exists) { const res = doc.data() as Question; // 直接用await获取缓存用户,确保res.from/to是User类型而非Promise res.from = await this.authService.userCache(doc.data().from.id); res.to = await this.authService.userCache(doc.data().to.id); return res; } else { console.warn(`There is no document for id ${id}!`); return null; } } catch (error) { console.warn("There was an error getting your document:", error); return null; } }
可选:优化userCache方法(同步风格)
async userCache(id: string): Promise<User | null> { const cachedUser = localStorage.getItem(id); if (cachedUser) { console.log("User found in cache"); return JSON.parse(cachedUser) as User; } else { console.log("User not found in cache. Caching..."); try { const user = await this.getSingleUser(id); if (user) { localStorage.setItem(id, JSON.stringify(user)); console.log("User cached"); console.log("User:", JSON.stringify(user)); } return user; } catch (err) { console.warn(err); return null; } } }
内容的提问来源于stack exchange,提问作者Felix
相关产品推荐
相关产品推荐

