The borders of the Stans were drawn during the Stalin era and the weirdness is caused primarily by where the ethnic groups were living at the time. Still they were trying to keep the weirness to a low. Samarkand, for example, was a Tajik speaking city in an Uzbek speaking region. Still it was given to Uzbekistan.
Legal reason for weirdness might be necessity for each of the Soviet Republics to have an access to non-Soviet territory. Else it could only be an Autonomous Republic inside of another Soviet Republic (like Abkhazia in Georgia, Chechnya in Russia or Karakalpakstan in Uzbekistan).