我试图在我的操作中调用一个函数,但出现错误 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
被定义为一个独立函数,而不是一个实例的属性,或当前 this
的属性,或类似的东西:
async function setToken() {
因此,调用它就像调用任何其他函数一样,无需将 this
放在它前面。
您也不能在内部作用域中使用相同的变量名称,否则您将引用内部变量(它将以undefined
/uninitialized 开头);将结果分配给不同的变量名:
const token = await setToken();
但是您当前的代码没有setToken
解析任何东西,在这种情况下,您可以简单地await
它,而不将结果分配给任何东西:
await setToken();
关于javascript - this.setToken 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55512441/