简体   繁体   中英

A weird error of variable not defined inside a function

I am writing a helper function called flattenErrorObj inside the register.js which contains redux actions. This helper method just flatten a object which contains key & array values.

function flattenErrorObj(errObj) {
    errorList = []
    
    for(const prop in errObj){
      
      errObj[prop].forEach((item)=>{
        errorList.push(prop +': '+item)
      });
    }
    return errorList;
}

export function registerUser(payload) {
    return (dispatch) => {

        dispatch(requestRegister());


        if (payload) {
            axios({
                url: '/users/create',
                method: 'post',
                headers: {
                    'Content-Type': "multipart/form-data"
                },
                data: payload
            }).then(res => {
                dispatch(receiveRegister());
                
                successToast(res.data.message)

            }).catch(err => {
                console.log('Error',err.response.data);
                errorToast(flattenErrorObj(err.response.data))
            })

        } else {
            dispatch(registerError('Something was wrong. Try again'));
        }
    };
}

I am getting this weird error,

Failed to compile

./src/actions/register.js
Line 28: 'errorList' is not defined no-undef
Line 33: 'errorList' is not defined no-undef
Line 36: 'errorList' is not defined no-undef

Even if I change the name of errorList variable I am still getting this error,saying that variable is not defined.I am new to reactjs, So am I doing anything wrong here?Any help would be appreciated.

You are probably running react in strict mode. You can not create variable without keywords. Use let errorList = [];

To define a variable, you must use var , let or const . Please refer https://www.w3schools.com/js/js_variables.asp .

Use one of the following

var errorList = []

let errorList = []

const errorList = []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM