首页 > 解决方案 > 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));
            });
    };
}

有任何想法吗?

标签: javascript

解决方案


setToken被定义为一个独立的 function,而不是一个实例的属性,或者 current this,或者类似的东西:

async function setToken() {

所以,像调用任何其他函数一样调用它,而不是放在this它前面。

您也不能在内部范围内使用相同的变量名称,否则您将引用内部变量(它将以undefined/ 未初始化开始);将结果分配给不同的变量名:

const token = await setToken();

但是您当前的代码没有setToken解决任何问题,在这种情况下,您可以简单地解决await它,而不将结果分配给任何东西:

await setToken();

推荐阅读