Quick answer: Override ExitState to clear timers, cancel async handles, and reset transient state. Don’t rely on next-task transitions to clean up previous task’s side effects.

An AI uses State Tree: PatrolState → ChaseState. Patrol task schedules a “say hello” timer; player triggers chase before it fires. The hello plays during chase. Task didn’t cancel its timer.

State Tree Task Lifecycle

Cancel Timers in ExitState

struct FPatrolTask : public FStateTreeTaskBase
{
    FTimerHandle HelloTimer;

    virtual EStateTreeRunStatus EnterState(FStateTreeExecutionContext& Ctx, const FStateTreeTransitionResult&) override
    {
        UWorld* World = Ctx.GetWorld();
        World->GetTimerManager().SetTimer(HelloTimer, [this]() { PlayHello(); }, 3.0f, false);
        return EStateTreeRunStatus::Running;
    }

    virtual void ExitState(FStateTreeExecutionContext& Ctx, const FStateTreeTransitionResult&) override
    {
        Ctx.GetWorld()->GetTimerManager().ClearTimer(HelloTimer);
    }
};

EnterState starts timer; ExitState cancels it. No straggler effects.

Async Action Handles

Similar pattern for FAsyncAction, FStreamableHandle:

virtual void ExitState(...) override
{
    if (PreloadHandle.IsValid()) {
        PreloadHandle->CancelHandle();
        PreloadHandle.Reset();
    }
}

Idempotent Cleanup

ExitState might be called from various paths (transition, tree reset, owner destroyed). Make cleanup safe to call twice. Use IsValid checks, then null out handles.

FinishTask Discipline

If your task represents finite work (“walk to point”), call Ctx.SetRunStatus(EStateTreeRunStatus::Succeeded) in Tick when done. Otherwise the task hangs and the state never transitions.

Verifying

Transition between states quickly. No leftover behavior from prior state (timers, sounds, animations). Tree debug visualizer shows clean state changes. AI feels reactive.

“EnterState starts work, ExitState cleans up. State Tree tasks must own their lifecycle.”

For combat AI especially, leaked timers cause “ghost taunts” or phantom animations after enemy death. Strict ExitState discipline avoids embarrassment.