to quote the lolwikia page on minion behaviour
Behaviour
Minions walk along a lane until they find an enemy unit. When they find an enemy unit, they attack it. When they find several enemy units they choose their target using a priority system that follows this order:
Enemy champions attacking an allied champion.
** Enemy minions attacking an allied champion.
Enemy minions attacking an allied minion.**
Enemy turrets attacking an allied minion.
Enemy champions attacking an allied minion.
The closest enemy minion.
The closest enemy champion.
** Once a minion has chosen a target, it only switches to a new target if the new target has higher priority. If they see a new target with the same priority as their current target, they keep attacking their current target.**
Minions reevaluate their target every few seconds. For instance, if an enemy champion attacks an allied champion and then stops attacking, minions will keep targeting the enemy champion for a short time after he stops attacking.
every few seconds is the RNG component since there is no specified timer that Riot has given us. Which means it's most likely a randomized value since the community can't find it out either.
minions being programmed to "defend other minions" is what probably prompts minions during these randomized checks to switch targets. If a minion randomly decides to check, and it sees another minion vs minion battle, (which will usually be how the minions get low on hp for last hitting) it will switch and attempt to assist. Which can fuddle with last hits and because the timer on when it checks being RNG, feels really unlucky.
What really annoys me personally though, is when I auto a minion and they just randomly decide to drop their minion vs minion battles, ignore the rules (priority on the list, is to defend itself from other minions before defending itself from champions) and suddenly start hitting me.