The grammar structure なり expresses that as soon as or the moment one action occurs, another action immediately follows. It conveys a sense of surprise, unexpectedness, or immediacy – the second action happens so quickly after the first that there is virtually no gap between them.
なり attaches to the dictionary form (plain non-past) of a verb. The subject of the first clause and the subject of the second clause are typically the same person.
The second action is usually involuntary, surprising, or dramatic. This sets なり apart from similar grammar like 〜~たとたん or 〜~やいなや. Using なり implies something noteworthy or unexpected happened right away.
The second clause typically describes a completed action (past tense). It is unnatural to use なり with commands, requests, intentions, or volitional expressions in the second clause.