javascript - this.setToken 不是函数
问题描述
我试图在我的操作中调用一个函数,但得到错误this.setToken is not a function
:
async function setToken() {
const {
credentials: { year, group, student }
} = this.props;
const fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
firebase
.firestore()
.collection("users")
.doc(fcmToken)
.set({
year
})
.then(function() {
return true;
})
.catch(function(error) {
return false;
});
}
}
export function fetchEvents(id) {
const currentDateString =
moment().format("YYYY-MM-DD") + "T" + "07:00:00.000Z";
const url = xxx;
return async dispatch => {
dispatch(isLoading(true));
const setToken = await setToken(); // call here
fetch(url)
.then(response => {
return response;
})
.then(response => response.json())
.then(data => {
const { error } = data;
if (error) {
dispatch(hasErrored(error.message));
} else {
dispatch(fetchSuccessEvents(data.items));
}
navigate("Month");
dispatch(isLoading(false));
});
};
}
有任何想法吗?
解决方案
setToken
被定义为一个独立的 function,而不是一个实例的属性,或者 current this
,或者类似的东西:
async function setToken() {
所以,像调用任何其他函数一样调用它,而不是放在this
它前面。
您也不能在内部范围内使用相同的变量名称,否则您将引用内部变量(它将以undefined
/ 未初始化开始);将结果分配给不同的变量名:
const token = await setToken();
但是您当前的代码没有setToken
解决任何问题,在这种情况下,您可以简单地解决await
它,而不将结果分配给任何东西:
await setToken();
推荐阅读
- android - 对嵌套的 Flavors 使用不同的 manifestPlaceholder
- javascript - javascript将数组转移到新数组
- python - 这段代码中的-1是什么意思([file for file in os.listdir(folder_dir) if file.find("xlsx") != -1])?
- ruby-on-rails - 删除用户时如何删除用户相关数据?
- python - 使用 awk 根据某些行中的值过滤文本文件
- formula - 如何解决 LibreOffice Calc 中的函数错误
- ms-access - 如果访问查询中的语句根据订购的数量从 1 个产品中选择 2 个价格
- reactjs - 以一定间隔渲染标记
- c# - 如何使 Unity 游戏对象变量只能从检查器编辑
- android - Android 聊天气泡概述了自定义设计