无法针对未安装的组件错误执行反应状态更新

时间:2020-03-26 18:23:25

标签: reactjs ionic-framework use-effect

我将在此简短介绍我已经参加了几个小时,并觉得我已经尝试了所有方法。我还从组件中遗漏了很多代码,认为与该问题无关。当用户尝试编辑史诗对象(在db中输入)时,用户将看到此组件EditEpic。在这里,用户还可以从数据库中删除对象,这是我现在要尝试的操作。删除后,用户将被带回到上一页。那就是我要解决的问题。这是代码

interface IEditEpic extends RouteComponentProps<{
    id: string;
}> {
}

interface IProps {
    updater?: (val:number) => void;
}

export const EditEpic: React.FC<IEditEpic> = ({match}, props:IProps) => {
    const [showAlert2, setShowAlert2] = useState(false);
    const [showAlert3, setShowAlert3] = useState(false);
    const [showAlert4, setShowAlert4] = useState(false);
    const [showAlert5, setShowAlert5] = useState(false);
    const [showAlert6, setShowAlert6] = useState(false);
    const [showAlert7, setShowAlert7] = useState(false);
    const [showAlert8, setShowAlert8] = useState(false);
    const [showAlert9, setShowAlert9] = useState(false);
    const [showAlert10, setShowAlert10] = useState(false);
    const [showAlert11, setShowAlert11] = useState(false);
    const [showAlert12, setShowAlert12] = useState(false);
    const [resultMessage, setResultMessage] = useState();
    const [epic, setEpic] = useState<any>();
    const [pet, setPet] = useState({petPoints: 0, id: ""});
    const history = useHistory();
    const [triggerRefresh, setTriggerFresh] = useState(0);

    useEffect(() => {
        let isSubscribed:boolean = true;
        if (isSubscribed) {
            (async () => {
                const res = await findEpic(match.params.id);
                if (res){
                    console.log("found epic ", res[0]);
                    setEpic(res[0]);
                }
                // set pet
                var my_pet:any = await getPet();
                if (my_pet)
                    if (my_pet.length > 0) {
                        setPet({petPoints: my_pet[0].points, id: my_pet[0]._id});
                    }
            })();
        }
        return () => {isSubscribed = false};
    }, [pet.petPoints]);


    const removeEpic = () => {
        (async () => {
            const result = await deleteEpic(epic);
            if (result === DELETE_EPIC_RESULT.pass)
            {
                console.log("Successful delete");
                setShowAlert7(true);
                console.log("going back in history");
                history.goBack();
            }
            else if (result === DELETE_GOALS_IN_EPIC_RESULT.fail)
                setShowAlert11(true);
            else if (result === DELETE_EPIC_RESULT.id_error)
                setShowAlert12(true);
            else
                setShowAlert6(true);
        })();
    };

    console.log("MY props updater", props.updater);

    return (
        <IonPage>
            <IonContent>
                <IonHeader>
                    <IonToolbar>
                        <IonButtons slot="start">
                            <IonBackButton defaultHref="/home" icon="buttonIcon"/>
                        </IonButtons>
                    </IonToolbar>
                </IonHeader>
                <IonList>
                    <div style={{display: "flex", justifyContent: "center"}}>
                        <h1 style={{fontWeight: "bold", textDecoration: "underline"}}>Edit Epic</h1>
                    </div>
                    <br/>
                    <IonItem>
                        <IonInput
                            value={epic?.epicTitle}
                            placeholder="Title"
                            required={true}
                            debounce={750}
                            clearInput={true}
                            minlength={1}
                            maxlength={50}
                            // onIonChange={e => setTitle(e.detail.value!)}
                            onIonChange={e => setEpic({...epic, epicTitle: e.detail.value!})}
                        >
                        </IonInput>
                    </IonItem>
                    <br/>
                    <br/>
                    <br/>
                    <IonItem>
                        <IonLabel position="floating">Description</IonLabel>
                        <IonTextarea
                            value={epic?.epicDescription}
                            placeholder="Please enter your description here"
                            onIonChange={e => setEpic({...epic, epicDescription: e.detail.value!})}>
                        </IonTextarea>
                    </IonItem>
                    <br/>
                    <br/>
                    <DateTimePicker dateType={DATE_ENUMS.start} setDate={setEpic} goalState={epic}/>
                    <br/>
                    <br/>
                    <DateTimePicker dateType={DATE_ENUMS.end} setDate={setEpic} goalState={epic}/>
                    <br/>
                    <br/>
                    <IonFab horizontal="end" vertical="top" slot="fixed">
                        <IonFabButton color="danger" onClick={() => setShowAlert5(true)}>
                            <IonIcon icon={trashOutline}/>
                        </IonFabButton>
                    </IonFab>
                    <IonAlert
                        isOpen={showAlert6}
                        onDidDismiss={() => setShowAlert6(false)}
                        header={'Error'}
                        message={DELETE_EPIC_RESULT.error}
                        buttons={["OK"]}
                    />
                    <IonAlert
                        isOpen={showAlert7}
                        onDidDismiss={() => setShowAlert7(false)}
                        header={'Success'}
                        message={DELETE_EPIC_RESULT.pass}
                        buttons={["OK"]}
                    />
                    <IonAlert
                        isOpen={showAlert11}
                        onDidDismiss={() => setShowAlert11(false)}
                        header={'Error'}
                        message={DELETE_GOALS_IN_EPIC_RESULT.fail}
                        buttons={["OK"]}
                    />
                    <IonAlert
                        isOpen={showAlert12}
                        onDidDismiss={() => {
                            setShowAlert12(false);
                            setTriggerFresh(triggerRefresh+ 1);
                        }}
                        header={'Error'}
                        message={DELETE_EPIC_RESULT.id_error}
                        buttons={["OK"]}
                    />
                    <IonAlert
                        isOpen={showAlert5}
                        onDidDismiss={() => {
                            setShowAlert5(false);
                            // close modal if the insert was successful
                        }}
                        header={'Delete Epic'}
                        message={"Are you sure that you would like to delete the selected epic? " +
                        "Goals associated with the epic will be deleted as well."}
                        buttons={[{
                            text: "NO",
                            handler: () => {
                                // do nothing
                            }
                        }, {
                            text: "YES",
                            handler: () => {
                                removeEpic();
                            }
                        }]}
                    />
                </IonList>
            </IonContent>
        </IonPage>
    )
};

export default EditEpic;

这里重要的是组件返回的最后一个IonAlert标签。在警报的按钮处理程序中,如果用户单击“是”,我将运行功能removeEpic()。这个功能删除了数据库中的史诗对象,而我想要发生的事情又回到了历史的最后一页,因为用户会删除他们正在查看的内容。当我把history.goBack()注释掉时,代码运行良好。

我一直在想问题可能是因为在异步函数中调用了history.goBack(),也许是因为该函数仍在进行中,并且我正在返回页面,所以反应会给我这个错误。但是,从removeEpic()中注释掉goBack()并将其放在IonAlert中的removeEpic()调用之后也不起作用。我不确定除此之外还能尝试什么。我也尝试了useEffect中的一些清理工作,但没有任何效果。任何帮助,将不胜感激。如果需要,我可以提供更多信息。

此外,我的堆栈跟踪看起来像这样

index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    in EditEpic (created by Context.Consumer)
    in Route (at App.tsx:66)
    in View (created by StackManagerInner)

1 个答案:

答案 0 :(得分:1)

这就是我要做的:

  1. 在您的const isMounted = useRef(true)组件顶部添加EditEpic
  2. 还有另一个(附加)useEffect,它看起来像这样:
useEffect(() => { return () => { isMounted.current = false} }, [])
  1. 在您拥有setSomething..的每一行代码中添加检查isMounted.current && setSomething..

想法是,使用useRef,您可以跟踪是否已安装组件,而仅在安装了组件时才更新状态。